title: Google map: Add click listener to each polygon
body: <p>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</p>
  
  <p>This is what I'm doing</p>
  
  <pre><code>map = new google.maps.Map(document.getElementById('map_canvas'),
      mapOptions);
  //Loop on the polygonArray
  for (var i = 0; i &lt; 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);
      });
  }
  </code></pre>
  
  <p><strong>Problem</strong></p>
  
  <p>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?</p>
  
  <p>Thanks</p>