This question already has answers here:
How do I return the response from an asynchronous call?
                            
                                (38个答案)
                            
                    
                2年前关闭。
        

    

我想从函数中返回当前用户的纬度和经度,并且我编写了以下代码,但是这段代码的结果是“未定义”。如果有人知道解决方案,请回答

<script>
function getLocation() {
    if (navigator.geolocation) {
        var lat_lng = navigator.geolocation.getCurrentPosition(showPosition);
        console.log(lat_lng);
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}
function showPosition(position) {
    var user_position = {};
    user_position.lat = position.coords.latitude;
    user_position.lng = position.coords.longitude;
    return user_position;
}
getLocation()
</script>

最佳答案

getCurrentPosition正在异步执行,并且console.log(lat_lng);已执行,然后才能从follow函数获取结果:

navigator.geolocation.getCurrentPosition(showPosition);

您必须改为使用callback函数。



function getLocation(callback) {
    if (navigator.geolocation) {
        var lat_lng = navigator.geolocation.getCurrentPosition(function(position){
        console.log(position);
          var user_position = {};
          user_position.lat = position.coords.latitude;
          user_position.lng = position.coords.longitude;
          callback(user_position);
        });
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}
getLocation(function(lat_lng){
  console.log(lat_lng);
});





Working solution.

09-25 15:51