Adding multiple markers with infowindows (Google Maps API)

Javascript has a language structure called “closures”. Closures are functions (such as the function() {} you declare above to deal with click listener) which capture references to external variables.

There are plenty of resources which explain them better than I can, which I suggest you consult, but here’s my best attempt:

In this block here:

    google.maps.event.addListener(markers[key], 'click', function() {
      infowindows[key].open(map, markers[key]);
    });

Because “key” is already defined as an external variable, the function will capture a reference to that variable. So where you expect:

infowindows["helloworld"]

Javascript will instead interpret this as:

infowindows[reference to key]

When you click on a marker, it looks up “reference to key” to see what the current value of key is. Because this probably won’t happen until your loop has finished, key will be equal to whatever the last key in your data.markers object is. And it will be equal to that value for EVERY click listener you added.

The solution, as you point out, is to wrap this in an anonymous function to get Javascript to evaluate the value of “key” at the time that the click listener is added.

  google.maps.event.addListener(markers[key], 'click', function(innerKey) {
      return function() {
          infowindows[innerKey].open(map, markers[innerKey]);
      }
    }(key));

Leave a Comment