我只是想将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/