谷歌地图:点击监听器添加到每个多边形 [英] Google map: Add click listener to each polygon
问题描述
我工作的web应用。
我有一个谷歌地图,在这里我从阵列添加多边形。我通过数组循环和多边形添加到地图。我还需要一个事件监听器添加到多边形点击并提醒多边形的位置
I am working on a webapplication. I have a google map, where I add polygons from an array. I loop through that array and add the polygons to the map. I also need to add an event listener to the polygon click and alert the position of the polygon
这是我在做什么。
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);
});
}
问题
的多边形绘图全部正确。然而,问题是,当我尝试点击一个多边形它总是显示最后一个索引。它像它只是点击最后一个多边形补充说。我想,当我添加一个新的监听器,它会覆盖旧的。我如何添加一个侦听器,以提醒正确的指数上涨了每个多边形?
The polygons are all drawing correctly. However the problem is that when I try to click on a polygon it always shows the last index. it is like it is only clicking on the last polygon added. I think when I add a new listener it overrides the old one. How can I add a listener for each polygon added in order to alert the correct index?
感谢
推荐答案
这是正常行为。
有两种解决方案,我能想到的:
It's the normal behavior. There is two solutions that I can think of :
1)我相信你可以从上下文找回来多边形(我没有测试):
1) I am sure you can find back the polygon from the context (I didn't test it):
google.maps.event.addListener(polygon, 'click', function (event) {
alert(this.indexID);
});
2)您也可以使用一些封的:
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);
}
这篇关于谷歌地图:点击监听器添加到每个多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!