JS Geolocation wait until success before return value(JS Geolocation 等到成功再返回值)
问题描述
我尝试开发浏览器地理定位,但似乎地理定位在仍在搜索我的位置时会很快返回一个值.
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}
)
}
如果我们执行这个脚本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 Geolocation 等到成功再返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JS Geolocation 等到成功再返回值


- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01