JS地理位置等到成功返回值之前 [英] JS Geolocation wait until success before return value
本文介绍了JS地理位置等到成功返回值之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的脚本示例:
我试图开发浏览器地理定位,但似乎地理定位很快在返回值时仍然在搜索我的位置。
$ b $
Example of my script:
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}
)
}
如果我们执行这个脚本 updateCoordinate
,函数将返回 undefined
。但是过了一会儿,如果我们检查了cookie,它就会设置坐标。
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等待,直到返回值之前得到精确坐标?
How to make getCurrentPosition waiting until get exact coordinate before returning the value?
推荐答案
使用回调函数,而不是超时会导致各种问题。有些内容符合:
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);
}
)
}
这篇关于JS地理位置等到成功返回值之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文