Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Google map: Add click listener to each polygon

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

This is what I'm doing

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

Problem

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?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...