I’ve got this piece of code where I’m trying to position a set of markers in a google map:
for(var i = 0; i < postcodes.length; i++) {
var address = postcodes[i].innerHTML +", uk";
geocoder.geocode({'address': address}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[i].geometry.location,
map: map,
icon: image,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
However, this returns as undefined where I try to set the position. If I use a number (0) instead of the variable i in results[#] it works fine but I can’t iterate through the results then. Has anyone come across this problem before?
Thanks,
The problem is that start one for loop that iterates through the postal codes:
So i is an index in the array of postcodes. Then you try to use that index in the object of results return from your geocoding request for postcodes[i]; but the two arrays are unrelated. Variable results is the results for postcodes[i], and contains all the search results for that postcode. Therefore, results[0] is the closest result to one postcode.
I think what you want is:
If you only want to show the closest results, omit the second for loop and use results[0] instead of results[i].