的問題是,當你喜歡你先做定義與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