user1430841
user1430841

Reputation: 47

Adding listeners to markers doesn't work in a loop

I'm trying to add listeners to markers in a loop but it doesn't work.

When adding them separately it works. Like this:

    google.maps.event.addListener(markersArr[0], 'click', function() {
        infoWindowArr[0].disableAutoPan=true;
        infoWindowArr[0].open(map,markersArr[0]);
    });

    google.maps.event.addListener(markersArr[1], 'click', function() {
        infoWindowArr[1].disableAutoPan=true;
        infoWindowArr[1].open(map,markersArr[1]);
    });

But when adding in a loop, clicking on a marker doesn't popup the infoWindow.

        for (var u=0; u<2; u++){
             google.maps.event.addListener(markersArr[u], 'click', function() {
             infoWindowArr[u].disableAutoPan=true;
             infoWindowArr[u].open(map,markersArr[u]);
        });

Can anyone explain how to make it work in a loop?

Upvotes: 1

Views: 522

Answers (2)

Heitor Chang
Heitor Chang

Reputation: 6057

I had the same situation and Engineer answered with an anonymous function wrapper. It would look like this. It's more compact but less readable than creating a side function.

    for (var u=0; u<2; u++){
      (function(u) {
         google.maps.event.addListener(markersArr[u], 'click', function() {
           infoWindowArr[u].disableAutoPan=true;
           infoWindowArr[u].open(map,markersArr[u]);
         });
      })(u);
    }

Upvotes: 1

lanzz
lanzz

Reputation: 43168

Your problem is that the listener function references the u variable, that is defined in an outer scope, and changes outside the function, i.e. at the time your listener runs, it will see u == 2, because the loop has already finished.

You could wrap your listener in another closure:

function makeListener(index) {
    return function() {
        infoWindowArr[index].disableAutoPan=true;
        infoWindowArr[index].open(map,markersArr[index]);
    }
}

for (var u=0; u<2; u++){
    google.maps.event.addListener(markersArr[u], 'click', makeListener(u));
}

Upvotes: 2

Related Questions