0

Hi I have a google maps polygons array named regionPolygons. Now I want each time I click a polygon, my map will set its center at that of the polygon. Here is how I implement it.

for (i = 0; i < regionPolygons.length; i++) {
  google.maps.event.addListener(regionPolygons[i], 'click', function () {                
    // do the stuff, things seem ok here
  }
}

Now whichever polygons I click, I am taken to the center of the last polygon. How can I let Google maps now which polygon is clicked? Thank you

Edit: My question a duplicate. It seems that copying the same code to the new function work. It seems that Javascript create new copy of the variable when it is passed from the main program to a sub program. Could any one help me explain about it?

0

1 Answer 1

1

It would be sensible for Google to make the clicked polygon available within the event handler as this or as event.target but the API documentation gives no clues that that's actually done. By all means try.

If neither of those suggestions works, then you can exploit a closure to keep a copy of i, as follows :

for(var i=0; i<regionPolygons.length; i++) {
    google.maps.event.addListener(regionPolygons[i], 'click', (function(i) {
        return function() {
            var polygon = regionPolygons[i];
            //do stuff here with `polygon`
        };
    })(i));
}

Alternatively, you could use the same technique to keep a reference to the polygon object itself :

for(var i=0; i<regionPolygons.length; i++) {
    var p = regionPolygons[i];
    google.maps.event.addListener(p, 'click', (function(polygon) {
        return function() {
            //do stuff here with `polygon`
        };
    })(p));
}

The nett effect is the same; inside the event handler, you end up with a reference to the clicked polygon.

Sign up to request clarification or add additional context in comments.

3 Comments

It seems that your methods did not work for my code. Nevertheless, I really appreciate your help :). Thank you.
Total success still depends on what you write to replace the placeholder "do stuff here with `polygon".
The same thing works if I copy the do stuff here to a new function. I would try your solution again though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.