Currently experimenting with Google Maps and the Geocoder, my goal is to iterate through a list of addresses, retrieve LatLng coordinates for each one, and then use that data to create markers using the setMarker
function provided below.
The issue I'm encountering is that the value of response[a]
keeps getting overwritten by the last address in the list due to the for loop outpacing the AJAX responses. How can I preserve the correct data associated with the current response[a]
during the iteration, so that it's available when setMarker()
is eventually called?
Any insights or suggestions would be greatly appreciated. Thank you!
var limit = 0;
for (a in response){
if(limit<5){ // limiting API calls
var addr = [response[a].Addr1, response[a].City, response[a].Zip];
geo = new google.maps.Geocoder();
geo.geocode({
address: addr.join(", "),
componentRestrictions: {
// country: 'UK'
}
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if(latitude!="" && longitude!=""){
bounds.extend(latlng);
map.fitBounds(bounds);
_this.setMarker(map, limit, latlng, response[a]);
}
} // if geo results
});
}
limit++;
}