Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GMaps v3 Markers AddListener Getting always the last variable index in the for loop

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

like image 244
Santiago Avatar asked Jun 27 '12 23:06

Santiago


1 Answers

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);
 }
like image 181
geocodezip Avatar answered Jan 03 '23 07:01

geocodezip