0

I have an array of 7 marker points , I want to add a click handler to each marker. I am trying to do so like this

for (var i = 0; i <= 7; i++) {
     google.maps.event.addListener(googleMarkerPoints[i], 'click', function () {
     var selector = "div[data-num='" + i + "']";
     $(selector).css({ "background-color": "#999" });
  });
}

googleMarkerPoints is filled like this:

for (var i = 0; i < data.length; i++) {
      var obj = data[i];
      var latitude = obj.Latitude;
      var longitude = obj.Longitude;
      var title = obj.Title;
      var thisLatlng = new google.maps.LatLng(latitude, longitude);
      var thismarker = new google.maps.Marker({
            position: thisLatlng,
            map: map,
            title: title
          });
      googleMarkerPoints.push(thismarker);
}

my problem is that every time that I click any marker in the handler selector gets filled with
"div[data-num='7']"

I was hoping that data-num would be different for each marker going 1 through 7, why are these click handlers not working properly??

Scott Selby
  • 9,420
  • 12
  • 57
  • 96
  • This is a FAQ. When the loop ends "i" is left at data.length+1. possible duplicate of [Google Maps JS API v3 - Simple Multiple Marker Example](http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example) – geocodezip Sep 11 '13 at 21:52

1 Answers1

1

You are closing over i and so you only get one value for all of the events. Try passing the i value into your anonymous function like this:

for (var i = 0; i <= 7; i++) {
 (function(i){
  google.maps.event.addListener(googleMarkerPoints[i], 'click', function () {
   var selector = "div[data-num='" + i + "']";
   $(selector).css({ "background-color": "#999" });
  });
 })(i)
}
Travis J
  • 81,153
  • 41
  • 202
  • 273