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 等到成功再返回值


基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01