如何在Javascript中返回用户的纬度和经度? [复制]

Posted

技术标签:

【中文标题】如何在Javascript中返回用户的纬度和经度? [复制]【英文标题】:how to return latitude and longitude of the user in Javascript? [duplicate] 【发布时间】:2017-10-02 08:42:50 【问题描述】:

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

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

getCurrentPosition 正在执行异步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.

【讨论】:

谢谢,我试试 @AbhayjeetSingh,我用一个可行的解决方案更新了它。

以上是关于如何在Javascript中返回用户的纬度和经度? [复制]的主要内容,如果未能解决你的问题,请参考以下文章