0

I have an array of objects (cards) which contain an id, latitude and longitude. I'm then building an array of markers to attach to a GoogleMap map:

for(var c = 0; c < cards.length; c++)
{
    var id = cards[c]["id"];
    var lat = cards[c]["lat"];
    var lon = cards[c]["lon"];

    var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lon)});
    marker.setMap(map);
    marker.addListener('click', function(){
        myListenerCallback(id);
    });
}

On each marker I want to attach a callback on the click event. It can be done quite easily by using the marker's .addListener method. The problem is, I want to fire a callback which includes the id of the card (as an input parameter): myListenerCallback(id). Looks like all the callbacks are firing using the last id of the array. How can I fire callbacks passing the corresponding id?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Gianluca Ghettini
  • 11,129
  • 19
  • 93
  • 159

2 Answers2

1

This is because when the event handler will be fired, the loop have finished it's execution and id is update with the last value of the array.

You can create a closure around the event handler function and pass the id

for (var c = 0; c < cards.length; c++) {
  //rest of the code
  (function(id) {
    marker.addListener('click', function() {
      myListenerCallback(id);
    });
  }(id))
}
brk
  • 48,835
  • 10
  • 56
  • 78
  • ok thanks. What are the memory implications of using a closure? What if I rerun the loop over and over? Does the set keeps growing or the functions get overwritten with the new ones (an identical set of course) – Gianluca Ghettini May 07 '17 at 09:44
1
cards.forEach(function(card){
  var id = card["id"];
  var lat = card["lat"];
  var lon = card["lon"];

var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lon)});
marker.setMap(map);
marker.addListener('click', function(){
    myListenerCallback(id);
});
});

See the duplicate post for a description...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151