Accessing loop iteration in a sub-function?
- by DisgruntledGoat
I'm using the Google Maps API to plot several points on a map. However, in the click event function below, i is always set to 4, i.e. its value after iterating the loop:
// note these are actual addresses in the real page
var addresses = new Array( "addr 1", "addr 2", "addr 3", "addr 4" );
for (var i = 0; i < addresses.length; i++) {
geocoder.getLatLng(addresses[i], function(point) {
if (point) {
var marker = new GMarker(point);
map.addOverlay(marker);
map.setCenter(point, 13);
GEvent.addListener(marker, "click", function() {
// here, i=4
marker.openInfoWindowHtml("Address: <b>" + addresses[i] + "</b>");
});
}
});
}
So when the marker displays it's using addresses[4] which is undefined. How do I pass the correct value of i to the function?