Reputation: 4169
for (var i=0; i<Gmaps.map.markers.length; i++) {
google.maps.event.addListener(Gmaps.map.markers[i].serviceObject, 'click', function(object){
alert(Gmaps.map.markers[i]);
});
};
So, this goes through the loop. I'm using this with the google maps API, obviously. Each of the markers on the map has the alert attached to it. The alert shows undefined
though. If I switch it to alert(Gmaps.map.markers[0]);
or any other applicable number, it shows me Object object, as it should. If I then call alert(Gmaps.map.markers[i].id);
or the like, I get the value I'm looking for, but obviously, every marker gives the same alert.
Why is the i
not being recognized in the callback?
Upvotes: 0
Views: 51
Reputation: 16726
you have to privatize the i:
for (var i=0; i<Gmaps.map.markers.length; i++) {
(function(i){
google.maps.event.addListener(Gmaps.map.markers[i].serviceObject, 'click', function(object){
alert(Gmaps.map.markers[i]);
});
}(i));
};
Upvotes: 1