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??

1

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.