So I have an array of objects with the following properties: Address
, Latitude
, Longitude
, and Title
poi("139 Main St", 0, 0, "Farmer's Market" ),
poi("18 N Hopkins Ave", 37.4455, -143.7728, "YMCA" ),
poi("42 Universe St", 37.4855, -143.8781, "Original Pizza #32" )
Now, the first object does not have anything set for latitude and longitude, so I was hoping to use Google's Geocode API to fill in the missing data. I included the API script link with my API key, which is working fine.
I then created a for
loop that goes through the array and finds any object with missing data. It's supposed to go through and replace any empty cells with the correct information. However, though the information is retrieved, it does so after the loop is completed. I can console out the correct information, but only after the function returns empty data.
for (i=0; i < poiArray.length; i++ ) {
var curr = poiArray[i];
if ( !curr.lat || !curr.long ) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': curr.address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
cur.lat = results[0].geometry.location.k;
cur.long = results[0].geometry.location.B;
} else {
console.log('failed to include ' + curr.title);
poiArray.splice(i--, 1);
}
});
}
}
I've tried timeout
and nesting functions, but nothing seems to work. Any suggestions?
Let me mention a bit more weirdness: if I console after if (status == google.maps.GeocoderStatus.OK) {
the variable i
in my for loop, I get the last number of my array... every time. And the loop only seems to update the last item in my array if I console my poiArray
after the asynchronous data from Google has loaded.