Close all infowindows in Google Maps API v3

前端 未结 11 1200
小蘑菇
小蘑菇 2020-12-08 00:01

I am busy with a script that will make a google maps canvas on my website, with multiple markers. I want that when you click on a marker, a infowindow opens. I have done tha

11条回答
  •  北海茫月
    2020-12-08 00:40

    I have something like the following

    function initMap()
    {
        //...create new map here
        var infowindow;
        $('.business').each(function(el){
            //...get lat/lng
            var position = new google.maps.LatLng(lat, lng);
            var content = "contents go here";
            var title = "titleText";
            var openWindowFn;
            var closure = function(content, position){.
                openWindowFn = function()
                {
                    if (infowindow)
                    {
                        infowindow.close();
                    }
                    infowindow = new google.maps.InfoWindow({
                        position:position,
                        content:content
                    });
                    infowindow.open(map, marker);
                }
            }(content, position);
            var marker = new google.maps.Marker({
                position:position,
                map:map,
                title:title.
            });
            google.maps.event.addListener(marker, 'click', openWindowFn);
        }
    }
    

    In my understanding, using a closure like that allows the capturing of variables and their values at the time of function declaration, rather than relying on global variables. So when openWindowFn is called later, on the first marker for example, the content and position variable have the values they did during the first iteration in the each() function.

    I'm not really sure how openWindowFn has infowindow in its scope. I'm also not sure I'm doing things right, but it works, even with multiple maps on one page (each map gets one open infowindow).

    If anyone has any insights, please comment.

提交回复
热议问题