問(wèn)題描述
我嘗試開發(fā)瀏覽器地理定位,但似乎地理定位在仍在搜索我的位置時(shí)會(huì)很快返回一個(gè)值.
I tried developing browser geolocation, but it seems geolocation quickly return a value when it is still searching for my location.
我的腳本示例:
function updateCoordinate() {
navigator.geolocation.getCurrentPosition(
function (position) {
setTimeout(function() {
var returnValue = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
var serializeCookie = serialize(returnValue);
$.cookie('geolocation', serializeCookie);
return serializeCookie;
}, 5000);
},
function () {
alert('Sorry, we are failed to get your location')
}, {timeout: 5000}
)
}
如果我們執(zhí)行這個(gè)腳本updateCoordinate
,函數(shù)會(huì)返回undefined
.但過(guò)了一會(huì)兒,如果我們檢查 cookie,它會(huì)正確設(shè)置坐標(biāo).
If we execute this script updateCoordinate
, the function will return undefined
. But after a moment if we check the cookie it set right the coordinate.
如何讓getCurrentPosition等到獲得精確坐標(biāo)后再返回值?
How to make getCurrentPosition waiting until get exact coordinate before returning the value?
推薦答案
使用回調(diào),而不是超時(shí),這會(huì)讓你遇到各種各樣的問(wèn)題.大致如下:
Use a callback, not a timeout which will end you up in all sorts of problems. Something along the lines of:
// Here you pass a callback function as a parameter to `updateCoordinate`.
updateCoordinate(function (cookie) {
console.log(cookie);
});
function updateCoordinate(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
var returnValue = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
var serializeCookie = serialize(returnValue);
$.cookie('geolocation', serializeCookie);
// and here you call the callback with whatever
// data you need to return as a parameter.
callback(serializeCookie);
}
)
}
這篇關(guān)于JS Geolocation 等到成功再返回值的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!