GMaps APIv3 InfoWindow for markers in loop for() i

2019-08-09 08:50发布

问题:

I know the topic has already been discussed many times, but I can't resolve my problem. I'd like to display some markers on my map, with a click event on each of them. Each click event should open an infoWindow with some data.

Here is what I wrote ; this code runs without any error in the console, all the markers are correctly displayed, but the infowindow displayed on click is always the same for all...

//Global variable
var info = new google.maps.InfoWindow();

//... some other functions

function createMarker(map)
{
    for(i = 0 ; i < loadedMarkers.length ; i++) { 
        (function(i) {
            value = loadedMarkers[i];
            var pos = new google.maps.LatLng(value.Latitude, value.Longitude);

            var mapOptions = {
                zoom: 10,
                center: pos,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            var marker = new google.maps.Marker({
                position: pos,
                map: map,
                title: value.Title
            });

            var MarkerContent = "<div class=\"marker\">" +
                                    "<h2>"+ value.Title +"</h2>" +
                                    "<p>"+ value.Text +"</p>" +
                                "</div>";

            info.setOptions({
                content: MarkerContent,
                size: new google.maps.Size(50, 50),
                position: pos
            });

            google.maps.event.addListener(marker, 'click', function () {
                info.open(map, marker);
            }); 
         }
       )(i);
    }
}

I heard about some closure problem (I'm new with JS), so I tried to put the logic in the (function(i) ...), but it always display the same content for all infowindow.

Could someone explain me where I'm wrong (and why ?)

Thanks you very much

回答1:

You need to update the content in the infowindow when it is opened (otherwise it displays the last content):

    google.maps.event.addListener(marker, 'click', function () {
        info.setOptions({
            content: MarkerContent
        });
        info.open(map, marker);
    });