简体   繁体   English

将地理位置坐标存储到变量将在控制台中返回未定义

[英]Storing Geolocation coordinates to variable returns undefined in console

I'm working on the weather app project on freeCodeCamp.org and am having some trouble storing the coordinates into variables. 我正在freeCodeCamp.org上从事天气应用程序项目,但在将坐标存储到变量中时遇到一些麻烦。 Here's what my code looks like so far. 到目前为止,这是我的代码。

function userLocation(){
    var lat = 0,
        lon = 0;

    if(navigator.geolocation){
      lon = navigator.geolocation.getCurrentPosition(lonPos);
      lat = navigator.geolocation.getCurrentPosition(latPos);
    }
    else{ alert("Geolocation not supported by this browser"); }

    return lat, lon;
}

function latPos(position){ return position.coords.latitude; }

function lonPos(position){ return position.coords.longitude; }

Inside the latPos() and lonPos() functions I can do console.log(position.coords.latitude) or longitude and get my coordinate. latPos()lonPos()函数内部,我可以执行console.log(position.coords.latitude)longitude并获取我的坐标。 However inside the userLocation() function the lat and lon variables return undefined . 但是,在userLocation()函数内部, latlon变量返回undefined What am I missing here? 我在这里想念什么? Here's a code pen to the project. 这是该项目的代码笔

从我的脑海中,仅查看您的代码,我想您应该调用latPos和lonPos,例如:navigator.geolocation.getCurrentPosition(lonPos())。

navigator.geolocation.getCurrentPosition()

takes a callback argument but it returns nothing. 接受回调参数,但不返回任何内容。

So your Best bet is to use Global Variables 所以最好的选择是使用全局变量

Something like this may work : 这样的事情可能会起作用:

EDIT : There seems to be some api calls happening so you will have to do what you want from within the callback. 编辑:似乎正在发生一些api调用,因此您将必须在回调中执行所需的操作。 Code below updated 下面的代码已更新

function userLocation()
{
  if(navigator.geolocation)
  {
    navigator.geolocation.getCurrentPosition(Position);
  }
  else
  { 
      alert("Geolocation not supported by this browser"); 
  }
}
function Position(pos)
{
  let lat = pos.coords.latitude;
  let lon = pos.coords.longitude;

  console.log(lat,lon);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM