1

I'm trying to make a Async call to Google Maps for address inside a foreach loop.

This is the function:

//Function to get address from geographic coordinates
        function getAddress(item) {
            var address = 'Not fetched';
            geocoder = new google.maps.Geocoder();
                var latlng = new google.maps.LatLng(parseFloat(item.Latitude), parseFloat(item.Longitude));
                geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK)
                        address = results[0].formatted_address;
                });
                return address;
        }

This is the loop:

 recreateMarkers: function (self, data) {
                        data.vehicleInfo.forEach(function (item) {
                            self.Location= getAddress(item);
                        });
                    }

Structure of Data: 1. VehicleId 2. Latitude 3. Longitude 4. Location

Now the problem is it gives me same or undefined location for all vehicles.

Would be glad if someone can assist.

Ashish Charan
  • 2,347
  • 4
  • 21
  • 33

1 Answers1

0

Here is the problem of asynchronous ,

return address is executed before google fetched address is assigned by address = results[0].formatted_address; so your function should be something like this

 function getAddress(item) {
            var address = 'Not fetched';
            geocoder = new google.maps.Geocoder();
                var latlng = new google.maps.LatLng(parseFloat(item.Latitude), parseFloat(item.Longitude));
                geocoder.geocode({ 'latLng': latlng }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK)
                        address = results[0].formatted_address;
                        return address; //<= this statement should be here
                });
           // Note return address; should not be here
    }
Suman Bogati
  • 6,289
  • 1
  • 23
  • 34