我有一个网络应用程序,询问用户他们的 GPS 位置。使用看起来像这样的漂亮标准代码可以正常工作:
function getpos_callback( a ) {
top.location.href = 'location.php?lat=' + a.coords.latitude + '&lon=' + a.coords.longitude;
}
function error_callback( er ) {
top.location.href = 'location.php?err=1';
}
if ( 'geolocation' in navigator ) {
navigator.geolocation.getCurrentPosition( getpos_callback, error_callback, {
enableHighAccuracy: true,
maximumAge: 300000, // 300 seconds = 5 min = max age of cached value to use
timeout: 8000, // 8 seconds
} );
}
这就是问题所在:在桌面浏览器上,确定位置可能需要相当长的时间(4-6 秒,根据代码长达 8 秒)。即使使用移动设备,有时它也可能很慢。当用户只想继续使用该网站时,这些秒感觉就像是永恒。
我想做的是让用户立即进入,但以某种方式“产生一个任务”来向浏览器询问后台的位置,然后在检索位置时让它在后台将该位置传递给我.
这可能吗?
最佳答案
方法navigator.geolocation.getCurrentPosition
根据定义是异步的。它由 W3C 指定立即返回。您可以查看the specification详情。
因此,您可以在调用 getCurrentPosition
后立即调用“让用户进入”的函数。在调用成功回调之前。方法getCurrentPosition
当你这样做时,将已经在后台“产生一个任务”。
您的代码中的问题是您在收到回调后更改网页的 URL,在 getpos_callback
内。功能。我建议您通过使用 JS 更新 UI 状态来更改此行为,而不是使用 lat/lng 参数重新加载页面。
重构你的代码,它看起来像:
function getpos_callback( a ) {
// Comment the line bellow to avoid loading the page
// top.location.href = 'location.php?lat=' + a.coords.latitude + '&lon=' + a.coords.longitude;
updateScreen(a.coords.latitude, a.coords.longitude);
}
function updateScreen(lat, lon) {
// Update the UI with the lat/lon received instead of getting it from the URL
}
function error_callback( er ) {
top.location.href = 'location.php?err=1';
}
function showUI() {
// "let the user in right away"
}
if ( 'geolocation' in navigator ) {
navigator.geolocation.getCurrentPosition( getpos_callback, error_callback, {
enableHighAccuracy: true,
maximumAge: 300000, // 300 seconds = 5 min = max age of cached value to use
timeout: 8000, // 8 seconds
} );
showUI();
}
else { error(); }
关于javascript - 是否可以在后台从桌面浏览器获取 GPS 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58698693/