Reputation: 225
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?
Upvotes: 0
Views: 102
Reputation: 16561
You're right, infoWindows[i]
is no longer accessible because the value of i
has been updated.
One way to solve this is to use .forEach
:
markers.forEach(function(value, i){
google.maps.event.addListener(markers[i], 'click', function() {
infoWindows[i].open(mymap, markers[i]);
});
})
In this case the i variable for each event listener is in a different function. Your current code uses the same i
variable every time and the i
variable in every event listener is the same. After all event listeners have been assigned i
remains at its final value and markers[i]
refers to the last marker in the list.
Check out this question for alternative solutions.
Upvotes: 1