简体   繁体   中英

Google Maps Geocode Not Working in For Loop

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 loop

  • Display 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?

我只是意识到我可以使用forEach而不必使用for循环,因为数据是从数组中提取的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM