【问题标题】:HTML5 geolocation lat and long coordinates of current GPS position into a variable将当前 GPS 位置的 HTML5 地理定位经纬度坐标转换为变量
【发布时间】:2023-03-25 02:00:02
【问题描述】:

我正在尝试通过利用 HTML5 的地理定位功能来获取用户的当前纬度和经度值。在研究并试图从 StackOverflow 上的其他问题中得到答案之后,我似乎仍然误解了访问全局变量的概念。到目前为止,我所看到的一切都表明范围似乎存在问题。我正在使用的代码看起来像是在函数中使用函数。我目前正在运行以下代码:

<script type="text/javascript">
var currentLat = 0;
var currentLong = 0;

function getPosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    console.log(position.coords.latitude);
    console.log(position.coords.longitude); 
}

getPosition();

此代码目前的工作原理是将信息记录到控制台。但是,如果我将代码更改为此它似乎不起作用:

<script type="text/javascript">
var currentLat = 0;
var currentLong = 0;

function getPosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    currentLat = position.coords.latitude;
    currentLong = position.coords.longitude; 
}

getPosition();

console.log(currentLat + "," + currentLong);

它只是像我最初设置的那样返回 0。我在全局变量上进行了很多搜索,但是大多数在线资源(包括 StackOverflow)都指出,只要我不在函数内重新声明变量(或创建覆盖全局变量的局部范围变量),我就可以访问这些变量)。

【问题讨论】:

  • 您的范围评估是正确的。但是,getCurrentPosition 是一个异步方法,将 showPosition 作为您的成功处理程序。因此,执行 console.log 时,您的 var 没有返回值。

标签: javascript html variables geolocation scope


【解决方案1】:

感谢 gro 的评论,我发现这行得通:

    window.onload = function(){
    navigator.geolocation.getCurrentPosition(function(position) {  
      window.currentLat = position.coords.latitude;
      window.currentLong = position.coords.longitude;
      window.currentLatLong = new google.maps.LatLng(currentLat,currentLong);
      init();
    });
}

function init() {
    // run code here and reference currentLatLong, currentLat and currentLong
}       

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多