Background to Question
I have an array which includes latitude and longitude values. I have the below code which places a marker for each iteration. I am using a Ruby gem Gon to pass values from the database to javascript. The below is working as expected:
function populateMap(map){
var index;
for (index = 0; index < gon.length; ++index) {
var latlng = new google.maps.LatLng(gon.murals[index].lat, gon.murals[index].long);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
}
}
However I want to have an info window for each marker with the address. This is done by reverse geo-coding. https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse.
The below code works for reverse geocoding 1 marker:
function getReverseGeocodingData(geocoder, map, infowindow) {
var latlng = new google.maps.LatLng(gon.murals[0].lat, gon.murals[0].long);
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'mouseover', function () {
infowindow.open(map, marker);
document.getElementById("address").innerHTML = results[1].formatted_address ;
});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
Actual Question When I add the for loop to the reverse geo0code function it only places the marker of the last iteration.
function populateMapTest(map, geocoder, infowindow){
var index;
for (index = 0; index < gon.murals.length; ++index) {
var latlng = new google.maps.LatLng(gon.murals[index].lat, gon.murals[index].long);
alert("start of iteration: " + index);
geocoder.geocode({'location': latlng}, function(results, status){
alert("middle of iteration: " + index);
if (status === 'OK') {
if (results[1]) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'mouseover', function () {
infowindow.open(map, marker);
document.getElementById("address").innerHTML = results[1].formatted_address ;
});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
alert("end of iteration: " + index);
}
}
For each iteration the alerts are in the following order: Start of iteration, end of iteration, middle of iteration. It seems to be skipping over the code contained in the geocoder brackets till all the iterations are done. I think?
Any help appreciated.