javascript - 卡在 JavaScript 变量闭包中

标签 javascript

我只是想将position.coords.latitude和经度分配给纬度和经度变量,但似乎我遗漏了一些东西,因为控制台总是说经度未定义。

function init() 
{
    var lat;
    var lon;

    if (navigator.geolocation) {

       navigator.geolocation.getCurrentPosition(function(position)
       {
          lat = position.coords.latitude;
          lon = position.coords.longitude;     
       });
    }

    console.log(lat);
    console.log(lon);

}

最佳答案

问题是,当您像最初一样使用 var 定义变量时,它们的值是未定义的。现在,当您调用 getCurrentPosition 函数时,它可能是异步的,这意味着在实际为它们分配任何值之前会调用 console.logs 。尝试以下更改

function init() 
{
    var lat;
    var lon;

    if (navigator.geolocation) {

       navigator.geolocation.getCurrentPosition(function(position)
       {
          lat = position.coords.latitude;
          lon = position.coords.longitude;  

          // Log them in the callback function
          console.log(lat);
          console.log(lon);  
       });
    }

}

由于您希望在获得坐标后执行实际代码,因此您可以通过以下方式更改 init 函数以适应异步架构。

// New function argument callbackFn - the function to call after 
// coords are loaded
function init(callbackFn) 
{
    // Removed local variables, no need for them here

    if (navigator.geolocation) {

       navigator.geolocation.getCurrentPosition(function(position)
       {
          var lat = position.coords.latitude;
          var lon = position.coords.longitude;  

          // This will be logged after the async call completes, probably after 
          // the console.log call below
          console.log("finished async call");

          // Execute the callback with coords
          callbackFn(lat, lon);
       });
    }

    // This will be called as soon as JS steps over previous lines, 
    // but before the asynchronous request has completed
    console.log("finished init");
}

假设您的实际程序在您执行名为 start 的函数(包含纬度和经度)时开始。在这种情况下,您将使用以下命令来启动您的程序:

function start(latitude, longitude) {
    // ... SNIP ... DO SOMETHING COOL
}

init(start);

关于javascript - 卡在 JavaScript 变量闭包中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9079272/

相关文章:

javascript - 如何从 slickgrid 中的代码提交单元格中的更改

javascript - 在 Javascript 中按函数优化分组

javascript - Angular 5 将日期绑定(bind)到字段( react 形式)

javascript - 使用设备上的 android 后退按钮返回到 Framework7 应用程序中的主视图?

javascript - React Native Get Async Storage 返回未处理的 Promise

javascript - 使用剩余空间将固定高度的 div 放置在容器底部,并使用另一个 div

javascript - 在尝试抓取 React 网站时获取 index.html 内容

javascript - ExpressJS 应用服务器在多次请求后返回 502

javascript - 有没有办法简化这段 JavaScript 代码? (多个类的相同功能)

javascript - $.extend 更改两个参数的值