0

Good morning,

I have a piece of JS reading a XML file and creating a series of Polygons, I have then added an action listener to those polygons.

However as part of that function I want to have the count variable past to the function.

// Code to read XML file then loop through...

for (var i = 0; i < zones.length; i++)

// Create a "new" dbpolygon

dbpolygon = new google.maps.Polygon
({paths : polygonPoints});

// add to array

zonepolygons.push(dbpolygon);
zonepolygons[zonepolygons.length - 1].setMap(map);


var userclick =  new google.maps.event.addListener(dbpolygon, 'click',  function() 
{    
load_sample_results(field,i);
});

So I'm creating a new polygon eachtime and then adding an action listener to that newly created polygon object. However the function always has the variable 'i' set to the last count of i and not the count at creation.

duncan
  • 31,401
  • 13
  • 78
  • 99
user2206836
  • 7
  • 1
  • 5
  • 1
    possible duplicate of [How do i open different information for each polygon i've created? Google maps api v3](http://stackoverflow.com/questions/13020757/how-do-i-open-different-information-for-each-polygon-ive-created-google-maps-a) – geocodezip Mar 25 '13 at 13:21
  • Is this your actual code? If so you're missing `{` `}` for your for-loop, so there's only one line executed within the loop, `dbpolygon = new google.maps.Polygon({paths : polygonPoints});` – duncan Mar 25 '13 at 13:58

1 Answers1

0

take a look at the answer from Shog9

you have to sourround your .addEventListener() with a let or with statement.

Community
  • 1
  • 1
DeBaum
  • 130
  • 1
  • 7
  • Perfect, I used to solution from Shog9 for (var i=0; i<3; ++i) { // variables introduced in this statement // are scoped to the block following it. let (num = i) { setTimeout(function() { alert(num); }, 10); } } – user2206836 Mar 25 '13 at 21:13