I’m trying to get a variable into an addListener function which is run inside a loop, but it always only takes notice of the last instance of the loop variable.
e.g.
for(var i=0; i < data.length; i++) {
points[i] = new google.maps.LatLng(parseFloat(data[i].lat), parseFloat(data[i].lng));
gmarkers[i] = new google.maps.Marker({
map: map,
position: points[i],
title: locationdata[i].title
});
gmarkers[i].setMap(map);
bubbles[i] = new google.maps.InfoWindow({
content: locationdata[i].summary
});
google.maps.event.addListener(gmarkers[i], 'click', function() {
alert(i);
bubbles[i].open(map, gmarkers[i]);
});
}
So the problem is that near the bottom the alert(i) is always the data.length’s last item, which makes sense, but I don’t know how to correct this.
Rocket answered this question and was correct, but the syntax was slightly off, so posting here what the real syntax was for anyone that comes across this later on:
google.maps.event.addListener(gmarkers[i], 'click', (function(i) {
return function() {
alert(i);
bubbles[i].open(map, gmarkers[i]);
}})
(i));
This is a classic issue in JavaScript. You need to make a closure for each of the listeners.