I'm using an array to store formatted results from google's geocoding API. After the function call I use console.log to see the contents of the array, which is working correctly, but when I try to access an individual element it returns "undefined". When I check the array length as well, I get zero. Here is my code (addressInput is an object storing three addresses):
function startGeocode(addressInput) {
var addressOut = [];
var outString = "";
var address = "";
for(var i = 0; i < addressInput.length; i++) {
address = addressInput[i].address + " " + addressInput[i].city + " " + addressInput[i].state + " " + addressInput[i].zip;
geocoder.geocode({'address':address}, function(results,status) {
if(status == 'OK') {
outString = "" + results[0].geometry.location;
outString = outString.replace(/\(|\)|\s/g,'');
outString = outString.replace(/\,/g,' ');
addressOut.push(outString);
} else {
outString = "Error: " + status;
addressOut.push(outString);
}
});
}
console.log(addressOut);
console.log(addressOut[0]);
console.log(addressOut.length);
}
The three console.log calls return the following:
/* (Using a codeblock for readability)
Array[0]
0:"(a correctly formatted latitude and longitude)"
1:"(a correctly formatted latitude and longitude)"
2:"(a correctly formatted latitude and longitude)"
addressOut[0]: undefined
addressOut.length: 0
*/
So my question is, why am I getting an array length of zero, and why am I not able to reference the elements of the array?