0

I am using google maps Geocoder to track coordinates of cities. I am not able to store the coordinates in an array. I am getting empty array. The coordinates exist inside the "if (status == google.maps.GeocoderStatus.OK)" but it is empty outside the loop.

function getcorrdinates(address){ 
    var result = "";
    var arr = [];
    var geocoder = new google.maps.Geocoder();
    for (var i = 0; i < address.length; i++) {
        geocoder.geocode({ 'address': address[i] }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK)
            {
                result = results[0].geometry.location;
                arr.push(result);
                alert ("Print Array inside the loop "+arr);//has value

            }
            else 
            {                                        
                        alert(" failed");

            }

        });
    }
   alert ("Print Array outside For loop "+arr); //is empty
return arr; 
}

So, here "alert "("Print Array inside the loop "+arr)" has values but when it is outside the loop it is empty and outside the loop gets executed first than the inside the loop. How can I store the values in a array so that I can use it for another function.

I am new to JavaScript, any help is appreciated.

  • 1
    I think this has something to do with the asynchronicity of the geocode method. – Mark Rijsmus May 14 '14 at 12:26
  • http://stackoverflow.com/questions/1310153/google-maps-api-geocode-synchronously http://stackoverflow.com/questions/5540979/geocode-sync-with-googlemaps – Mark Rijsmus May 14 '14 at 12:30

0 Answers0