Google map: Add click listener to each polygon

帅比萌擦擦* 提交于 2019-11-28 20:37:32
SuperSkunk

It's the normal behavior. There is two solutions that I can think of :

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) You could also use some 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);
}

Move the code block inside the for-loop.

//Add the click listener
    google.maps.event.addListener(p, 'click', function (event) {
        //alert the index of the polygon
        alert(p.indexID);
    });

OR

You add this to for-loop,

p.addListener('click', clickSelection);

and do this

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