0

I'm importing map data from an XML list and placing that in markerArray, then calling createMarkers(); The markers appear on the map ok, but clicking always goes to the last marker on the list.

All help appreciated.

function createMarkers() {
for (i=0; i<markerArray.length; i++){
 var marker = new google.maps.Marker({position:markerArray[i].latlng, map:map, title:markerArray[i].label, icon:images[markerArray[i].type]});
 google.maps.event.addListener(marker, 'click', function() {
        map.setZoom(9);
  map.setCenter(marker.getPosition());
    }); 
}

1 Answers1

3

marker is redefined with each loop iteration. The function bound to 'click' should be wrapped in a closure with a local copy of marker. I had to do something similar once and used this:

 google.maps.event.addListener(marker, 'click', 
   (function(marker_inner) {
      return function() {
        map.setZoom(9);
        map.setCenter(marker_inner.getPosition());
      }
   })(marker)
 ); 
giaour
  • 3,878
  • 2
  • 25
  • 27