简体   繁体   中英

get google api address value as return from javascript function

  • I am trying to get the address from the google maps api and return this address in the function.What do I need to change to make these show up?

$(document).ready(function() {
  var lat = 17.4807865;
  var lng = 78.4921649;
  var returnAddress = getAddressFromlatlng(function(backaddr,lat,lng){
     alert(" Inside : "+backaddr)
  });
  alert(returnAddress+" returned address ")
});
function getAddressFromlatlng(callback,lat,lng){
  alert(lat+" : "+lng)
  var geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(lat,lng);
  geocoder.geocode({'latLng': latlng}, function(results, status){   
    alert(results[0].formatted_address)
    callback(results[0].formatted_address);
  });
}

That's not possible, as the function returns before the value exists.

The geocode call is asynchronous, so you have to handle the result asynchronously. You already display the value successfully in the callback function, that is the way to handle the result.

You could return a promise from the getAddressFromlatlng function, but that doesn't really change anything. That's just wrapping the callback function in an object so that you can do the asynchronous handling of the result separate from the call.

You should be taking the address from the result of the callback. Once the coordinates have been resolved you call a function that continues processing the returned value because only then do you have the return value. In the case your going through an array use the array index and update the address field once you have the required data. or process them individualy. work through the array making a request to google for every item. once the response comes back from google, move onto the next item in your array. If you can save the index so its known when the response arrives then it would be possible to wait for multiple requests.

var currentIndex = null;
function notifyAddressResolved (address) {
    yourArray[currentIndex].address = address;
    resolveNextAddress();
}
function getAddressFromlatlng(callback, lat, lng){
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);  
    geocoder.geocode({'latLng': latlng}, function (results, status) {           
        callback(results[0].formatted_address);
    });
}
function resolveNextAddress () {
    if (currentIndex == null) {
        currentIndex = 0;
    } else {
        currentIndex++;
    }
    getAddressFromlatlng(notifyAddressResolved, yourArray[currentIndex].lat, yourArray[currentIndex].lng);
}

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