我正在尝试为每个标记(有30个标记)处理鼠标悬停,并显示这些标记的信息。我为每个标记创建了监听器,但当我的鼠标悬停在某个标记上时,它始终显示最后一个标记的infowindows。总结一下,我不能听其他标记。任何帮助,将不胜感激。在此先感谢我的代码:
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();
});
}
我也在使用js cluster library,但我不认为问题与此有关。
答案 0 :(得分:1)
我认为你的问题可能是你没有在循环中使用闭包,当触发事件监听器时,marker
和contentString
变量指向最后一个标记。 / p>
尝试重写这样的循环:
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);
}