I use http://tile.cloudmade.com/wml/latest/web-maps-lite.js to geocode.
There is a address array containing around 20 addresess
addresses[n] = {where:where,who:who,contact:contact,note:note,type:type};
Then I loop the array to geocode
for (var i = 0; i < addresses.length; i++) {
geocoder2.getLocations(addresses[i].where, function(response) { //a callback
return function(k){
Lat[k] = response.features[0].centroid.coordinates[0];
Lng[k] = response.features[0].centroid.coordinates[1];
latlng = new google.maps.LatLng(Lat[k], Lng[k]);
MarkerArray[k] = new google.maps.Marker({
map: map,
position: latlng,
zIndex: k,
title: addresses[k].who,
icon: icons(addresses[k].type.trim())
});}(i) // a closure function called
});
}
But the it always works on the final index. Why??
You have the Closure Loop Problem. You appear to be trying to fix it by adding the
return function(k)...closure, but that’s all occurring inside the callback function, so it won’t execute until the loop has exited andiis pointing at its final value.You would have to push that wrapper out a level so it’s directly inside the loop:
Or use Function#bind to avoid the nested function.