views:

44

answers:

1

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??

+1  A: 

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 and i is pointing at its final value.

You would have to push that wrapper out a level so it's directly inside the loop:

for (var i = 0; i < addresses.length; i++) {
    geocoder2.getLocations(addresses[i].where, function(k) { //a callback
        return function(response){
            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)); // binding *here* instead!
}

Or use Function#bind to avoid the nested function.

bobince
Your wrapper out solution works in Firefox, but in IE and Chrome....still got the same problem. I will take some time to look into the bind solution
ValidfroM
Very weird, all lat and lng are correct, but just title and icon are wrong...
ValidfroM