1

I'm using the Gmaps.js api in a little project I'm building and struggling with adding click events within a for loop. Here's the code:

for(var i = 0; i < number; i++) {
        var entryTime = data[i].datetime;
        map.addMarker({
            lat: data[i].lat,
            lng: data[i].lng,
            click: function(){
                alert(entryTime);
            }
        });
}

However, when clicking the markers I always get the last data element. How can I bind this function to each marker?

Lukas
  • 13
  • 3

1 Answers1

1

This is the expected behavior. The entryTime variable is defined and changed outside the click handler; and when the click handler is fired it will alert the last value assigned to entryTime.

One solution is to create a closure in order to create a copy of variables and their values at the time the closure was created.

for (var i = 0; i < number; i++) {
    map.addMarker({
        lat: data[i].lat,
        lng: data[i].lng,
        click: (function (t) {
            return function () {
                alert(t);
            };
        })(data[i].datetime)
    });
}

The details are explained in this question.

Community
  • 1
  • 1
Salman A
  • 262,204
  • 82
  • 430
  • 521