简体   繁体   中英

Google Maps listener closure

I am trying to add an info window to a marker by looping through an array of objects and creating the markers and then checking if the object has a content property, and if it does, then adding an event listener on the marker to open an info window.

I'm almost there but have run into a closure related problem in the loop. I always end up with the last object in the array's content property. I thought I could get around this by wrapping the event listener callback in a function and passing in the object

Can anyone tell me what I am doing wrong with my closure when assigning the event listener:

_addMarkers = function () {
    var marker, latlon, title, infowindow, content;

    _options.markers.map(function (marker) {

        title   = marker.title;
        content = marker && marker.window_content;
        latlon  = _getLatLon(marker.lat, marker.lon);

        if (latlon) {
            marker = new google.maps.Marker({
                position : latlon,
                title    : title,
                map      : _map
            });
        }


        if (content) {
            infowindow = new google.maps.InfoWindow({
                content: content
            });                        

            google.maps.event.addListener(marker, 'click', (function (_marker) { 
                infowindow.open(_map, _marker);
            }(marker)));
        }

    });
} 

Fixed it. Changed the bit adding the listener to:

if (content) {
    google.maps.event.addListener(marker, 'click', (function (content, _marker) { 
        return function () {
            infowindow = new google.maps.InfoWindow({
                content: content
            });                        
            infowindow.open(_map, _marker);                        
        };
    }(content, marker)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM