将经纬度保存在对象中

Save the latitude and longitude in an object

我想将经纬度保存在一个对象中。当我使用第一个 console.log 时,它也会显示纬度和经度。

当我尝试保存在变量中并在函数后使用 console.log 时,它什么也没显示。

怎么了?我读到那是关于 异步编程 但我不明白。

$(document).ready(function(){
var userPosition = 
{
    lat: '',
    lon: ''
};

    if(navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(function(position){
                userPosition.lat = position.coords.latitude;
                userPosition.lon = position.coords.longitude;
                console.log(userPosition.lat); //This shows me the latitude
            });
        }
        else
        {
            alert("Geolocation not supported by your browser");
        }

console.log(userPosition.lat);      // This not works

});

请遵循此代码。

$(document).ready(function(){
        var userPosition = 
        {
        lat: '',
        lon: ''};
        if(navigator.geolocation)
            {
                navigator.geolocation.getCurrentPosition(function(position){
                    userPosition.lat = position.coords.latitude;
                    userPosition.lon = position.coords.longitude;
                    console.log(userPosition.lat); //This shows me the latitude

                });
            }
            else
            {
                alert("Geolocation not supported by your browser");
            }
            setTimeout(function () {console.log('Updated::::'+userPosition.lat);},2500);
    });

setTimeout 不是推荐选项。(仅供测试。)

这里你没有得到 console.log('Updated::::'+userPosition.lat); 的纬度值 这是因为 navigator.geolocation 将花费很少的时间来获取数据,因此您需要放置 setTimeout 或在获得 lat 和 lng 之后从 if 部分调用函数价值。

更好的选择是在获取值后调用函数。

推荐使用方式如下:

if(navigator.geolocation)
            {
                navigator.geolocation.getCurrentPosition(function(position){
                    userPosition.lat = position.coords.latitude;
                    userPosition.lon = position.coords.longitude;
                    console.log(userPosition.lat); //This shows me the latitude
                    Displaylat_lng(userPosition.lat,userPosition.lon);

                });
            }

function Displaylat_lng(lat,lng){
            console.log('Lat ==> '+lat + ' lng ==> '+lng);
    }

是的,这是因为函数 navigator.geolocation.getCurrentPosition 是异步的。

这意味着在您的情况下,主要代码会立即运行。 navigator.geolocation.getCurrentPosition 传递给匿名函数,然后立即调用第二个 console.log。

navigator.geolocation.getCurrentPosition GPS 需要一些时间来反应,然后,才用第一个 console.log 调用匿名函数。

您有几种解决方案:

- put all you need to do with the location inside the callback function 
- put all you need to do with the location into a separate function and call it inside the callback 
- use promises. I recommend though that you understand the callback way thoroughly, before you try out promises. While the latter gives you clearer code, the concept is more difficult to grasp. 
- setTimeout : not recommended. Disadvantage : you don't know the it takes to get the current position. 

这是因为 navigator.geolocation.getCurrentPosition() 调用及其相关回调是异步发生的。 getCurrentPosition() 运行,但您传递给它的函数仅在 getCurrentPosition() 的实现调用它之后运行。 getCurrentPosition()之后的下一条指令是console.log(userPosition.lat);,但是userPosition.lat仍然是'',因为还没有调用异步函数。

使用 Promises,您可以 something like this 如果需要:

HTML

<div id="output"></div>
<div id="error"></div>
<button id="get-position">Get position</button>

JS

$(document).ready(function() {
  $('#get-position').on('click', getLocation);
  function getLocation(event) {
    try {
      const positionPromise = new Promise((resolve, reject) => {
        if ("geolocation" in navigator) {
          navigator.geolocation.getCurrentPosition(
            position => {
              resolve({
                lat: position.coords.latitude,
                lon: position.coords.longitude
              });
            },
            err => { reject(err); }
          );
        }
        else {
          reject("Geolocation not supported by your browser");
        }
      })
      .then(function(userPosition) {
        $('#error').empty();
        $('#output').html(`${userPosition.lat} x ${userPosition.lon}`); 
      }, errorHandler);
    } catch (err) {
      errorHandler(err);
    }
  }

  function errorHandler(err) {
    $('#output').empty();
    $('#error').html(err);
  }
});

使用以下方法

  $(document).ready(function(){
            var userPosition = 
            {
            lat: '',
            lon: ''};
            if(navigator.geolocation)
                {
                    navigator.geolocation.getCurrentPosition(function(position){
                        userPosition.lat = position.coords.latitude;
                        userPosition.lon = position.coords.longitude;
                        console.log(userPosition.lat); //This shows me the latitude 
                        foo(userPosition); // pass the resultant object to function for further processing

                    });
                }
                else
                {
                    alert("Geolocation not supported by your browser");
                }

        })

function foo(locationObj){
  // do rest of the coding for usage of latitude and longitude
}