The code below overwrites the var store every time the while loop runs. So when the callback runs the store value is usually the last item in the store array.
var stores = [];
stores.push({'address': "1 California Ave, San Francisco, CA"});
stores.push({'address': "16 California Ave, San Francisco, CA"});
stores.push({'address': "20 California Ave, San Francisco, CA"});
stores.push({'address': "30 California Ave, San Francisco, CA"});
var geocoder = new google.maps.Geocoder();
var i = 0;
while( i < stores.length){
var store = stores[i];
geocoder.geocode({'address':store.fullAddress}, function(data, status){
store.latlng = data[0].geometry.location;
}
});
i++;
};
How do I add the correct latlng to the correct store?
This doesn't work either because the var i is changed as well.
var i = 0;
var storesObject = {}
while( i < stores.length){
var store = stores[i];
storesObject[i] = stores[i];
geocoder.geocode({'address':store.fullAddress}, function(data, status){
storesObject[i].latlng = data[0].geometry.location;
}
});
i++;
};
If I do this how do I match the results to the stores array?
var i = 0;
var results = [];
while( i < stores.length){
var store = stores[i];
geocoder.geocode({'address':store.fullAddress}, function(data, status){
results.push(data[0].geometry.location);
}
});
i++;
};
UPDATE adding in a functional scope fixed my issue:
var i = 0;
while( i < stores.length){
(function(){
var store = stores[i];
geocoder.geocode({'address':store.fullAddress}, function(data, status){
store.latlng = data[0].geometry.location;
}
});
})();
i++;
};
see: GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?