why are my google maps event listeners not working properly?

时光毁灭记忆、已成空白 提交于 2019-12-13 00:56:44

问题


I'm trying to handle mouse over listener for each marker(there are 30 markers) and to show infowindows for these markers. I created listeners for each markers but when my mouse over the some marker it shows always the last marker's infowindows. To sum up I can't listen other markers. any help would be appreciated. thanks in advance and here my code :

var listeners = [];
for(var i = 0; i < markers.length; i++){
  var marker = markers[i];
  var contentString = contents[i];
  listeners[i] = new google.maps.event.addListener(marker, 'mouseover', function() {
    var hideInfoWindows = function(){
        for (var j = 0; j < util.Common.infowindows.length; j++) {
          util.Common.infowindows[j].close(); 
        }
    }
    var addInfoWindow = function(){
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });
        //hideInfoWindows();
        util.Common.infowindows.push(infowindow);
        infowindow.open(util.Common.googlemap,marker);
    }
    addInfoWindow();
  });
}

I'm also using js cluster library but I don't think the problem is related with it.


回答1:


I think your problem might be that you are not using a closure inside the cycle, and when the event listener is fired, the marker and the contentString variables are pointing to the last marker.

Try to rewrite the cycle like this:

var listeners = [];
for(var i = 0; i < markers.length; i++){
    (function(index){ //create a closure, variable 'index' will take its value from variable i, but won't be affected by changed i in the outer scope
        var marker = markers[index]; //use this scope's index variable instead of i
        var contentString = contents[index]; //use this scope's index variable instead of i
        listeners[index] = new google.maps.event.addListener(marker, 'mouseover', function() {
            var hideInfoWindows = function(){
                for (var j = 0; j < util.Common.infowindows.length; j++) {
                    util.Common.infowindows[j].close();
                }
            };
            var addInfoWindow = function(){
                var infowindow = new google.maps.InfoWindow({
                    content: contentString
                });
                //hideInfoWindows();
                util.Common.infowindows.push(infowindow);
                infowindow.open(util.Common.googlemap,marker);
            };
            addInfoWindow();
        });
    })(i);
}


来源:https://stackoverflow.com/questions/31983445/why-are-my-google-maps-event-listeners-not-working-properly

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