如何在Javascript中返回用户的经纬度?

时间:2017-10-02 08:42:51

标签: javascript geolocation geocoding

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

<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>

1 个答案:

答案 0 :(得分:0)

getCurrentPosition正在执行异步,并且在您从follow函数获得结果之前执行console.log(lat_lng);

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.