Edit - I have fixed this by using forEach
rather than a for loop since the items are pulled from an array
I'm using this code to retrieve the latitude and longitude of a given address to be used with leaflet.js.
markers = [
{
"name": "Tom David",
"address": "Karachi, Pakistan",
"url": "https://en.wikipedia.org/wiki/Anguilla"
},
{
"name": "Bob Thomas",
"address": "London, Canada",
"url": "https://en.wikipedia.org/wiki/Japan"
},
{
"name": "Bob Mike",
"address": "Paris, FR",
"url": "https://en.wikipedia.org/wiki/Japan"
}
];
for ( var i=0; i < markers.length; i++ ) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': markers[i].address}, function(results, status) {
L.marker([results[0].geometry.location.lat(), results[0].geometry.location.lng()]).bindTooltip(markers[i].address).addTo(map);
});
}
The problem lies with bindToolTip(markers[i].address)
as it seems to 'break' the code though when using a string name (like "Hello"
), it works just fine.
This is due to the loop not working as intended to after the new google.maps.geocoder()
part. I have tried using alert(i)
below the said code, and it just iterates the number 12
three times for some reason.
When it is placed above the geocoder()
part, it works correctly and iterates 0
, 1
, and 2
.
I would really appreciate any help with this.
Overall
Retrieve the address from the array based on the current
i
value in the for loopDisplay the address retrieved in the
bindTooltip()
part to be displayed as a tooltip value within the map.
Edit
Asynchronous Process inside a javascript for loop This question has been marked as a duplicate of the link shown, though I am unsure of how the answers provided could be used in my own. Could someone help me out with this?