我正在开发一个网络应用程序。
我有一个谷歌地图,我从一个数组中添加多边形。我遍历该数组并将多边形添加到 map 中。我还需要向多边形单击添加事件监听器并提醒多边形的位置
这就是我正在做的
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
//Loop on the polygonArray
for (var i = 0; i < polygonArray.length; i++) {
//Add the polygon
var p = new google.maps.Polygon({
paths: polygonArray[i],
strokeWeight: 0,
fillColor: '#FF0000',
fillOpacity: 0.6,
indexID: i
});
p.setMap(map);
//Add the click listener
google.maps.event.addListener(p, 'click', function (event) {
//alert the index of the polygon
alert(p.indexID);
});
}
问题
多边形都正确绘制。但是问题是,当我尝试单击多边形时,它总是显示最后一个索引。就像它只是单击添加的最后一个多边形。我认为当我添加一个新的监听器时,它会覆盖旧的监听器。如何为添加的每个多边形添加一个监听器以提醒正确的索引?
谢谢
最佳答案
这是正常的行为。
我能想到两种解决方案:
1)我相信你可以从上下文中找到多边形(我没有测试它):
google.maps.event.addListener(polygon, 'click', function (event) {
alert(this.indexID);
});
2) 你也可以使用一些 closures :
var addListenersOnPolygon = function(polygon) {
google.maps.event.addListener(polygon, 'click', function (event) {
alert(polygon.indexID);
});
}
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
//Loop on the polygonArray
for (var i = 0; i < polygonArray.length; i++) {
//Add the polygon
var p = new google.maps.Polygon({
paths: polygonArray[i],
strokeWeight: 0,
fillColor: '#FF0000',
fillOpacity: 0.6,
indexID: i
});
p.setMap(map);
addListenersOnPolygon(p);
}
关于javascript - 谷歌地图: Add click listener to each polygon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15208965/