I'm using Google Maps' API. I have an array of markers and an array of info windows, and I'm trying to get the respective info window to display when the marker is clicked. I'm having trouble understanding how I should add my event listener so that it respects JavaScript closures.
(Incorrect) Code, all of which is contained in an initialize()
that is called when the page loads:
var markers = []
var infoWindows = []
[define all markers and info windows here, long so cut]
for (var i = 0; i < markers.length; i++)
{
google.maps.event.addListener(markers[i], 'click', function() {
infoWindows[i].open(mymap, markers[i]);
});
}
I've made sure that all of my objects are initialized properly before coming here.
My understanding of my problem is that by the time the click event occurs, infoWindows[i]
is no longer accessible. What can I do about this so that the eventListener
works as I think it should, where the infoWindow
at the i-th position in the array corresponds to the marker at the i-th position?