的问题是,当你喜欢你先做定义与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);
});
}
}
既然你想你有COORDS后执行实际代码,这里是你如何可以改变你的初始化函数,以适应异步架构。
// 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");
}
让我们假装你的实际程序开始于你执行一个叫做经度和纬度开始的函数。在这种情况下,你可以使用下面的启动程序:
function start(latitude, longitude) {
// ... SNIP ... DO SOMETHING COOL
}
init(start);
是getCurrentPosition执行异步? (setTimeout/setInterval/AJAX) – TimWolla 2012-01-31 12:11:32
是异步。对不起,因为noob,但我怎么能让它同步? – 2012-01-31 12:15:37
当没有参数时:除修改脚本外没有办法。但可能这是第三方库,对吧? – TimWolla 2012-01-31 12:20:51