Unable to access array inside geocoder-Collection of common programming errors
The geocoder is asynchronous. The loop spins through all the possible values of i, leaving i set to postCode.length+1 which is undefined. This can be addressed with function closure (however, depending on the number of locations you have, you may have issues with the quota or rate limit):
function geocodeAddress(index) {
geocoder.geocode({'address': postCode[index]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat2 = results[0].geometry.location.lat();
var lng2 = results[0].geometry.location.lng();
var Latlng = new google.maps.LatLng(lat2, lng2);
var marker = new google.maps.Marker({
position: Latlng,
map: map,
title: titles[index],
icon: icon
});
} else { alert("geocode failed:"+status);
});
}
for(var i = 0; i < length; i++)
{
geocodeAddress(i);
}
Originally posted 2013-11-09 20:50:45.