GMaps v3 Markers AddListener Problem
I'm trying to add mouseover/mouseout event listener to my markers, but I get allways the last value of the for loop In all the events, It seems to get the last value of the for instead the current. Here is my code
for( mark in data ) {
markers[mark] = new google.maps.Marker({
position: new google.maps.LatLng(data[mark].lat,data[mark].lng), map: map,
});
google.maps.event.addListener(markers[mark], "mouseover", function() {
alert(mark);
});
google.maps.event.addListener(markers[mark], "mouseout", function() {
alert(mark);
});
}
The result is an alert on mouse over/out with the same value for all 10 markers and I was expecting the marker id on each alert.
thanks Regards
The problem you are having is the value of mark is global and is left set to the last value in the loop. The issue can be fixed with a function closure. I think this will work (not tested):
function createMarker(latlng, id)
{
var marker= new google.maps.Marker({
position: latlng, map: map,
});
google.maps.event.addListener(marker, "mouseover", function() {
alert(id);
});
google.maps.event.addListener(marker, "mouseout", function() {
alert(id);
});
return marker;
}
for( mark in data ) {
markers[mark] = createMarker(new google.maps.LatLng(data[mark].lat,data[mark].lng),
mark);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With