why are my google maps event listeners not working

2019-08-08 19:41发布

问题:

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