GMaps APIv3 InfoWindow for markers in loop for() is always the same

不羁的心 提交于 2019-12-11 13:23:26

问题


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);
    }); 


来源:https://stackoverflow.com/questions/17773574/gmaps-apiv3-infowindow-for-markers-in-loop-for-is-always-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!