我正在开发一个带有谷歌地图的网络应用程序,并使用 getCurrentPosition()
获取用户位置。这很好用,但我需要随着时间的推移跟踪用户位置。
为此,我打算使用 watchPosition()
。根据 API 引用 API reference它必须立即执行数据获取并执行回调,但它没有。相反,它卡住了,我不能再使用 getCurrentPosition()
。我一直在为此寻找原因,但我无法弄清楚为什么会这样。我使用的是适用于 Linux Mint“Lisa”的最新版 Chrome。
最佳答案
在移动设备上,.getCurrentPosition()
非常不准确。使用 .watchPosition()
更准确,但需要大约五秒钟才能获得最佳读数。之后,它会浪费电池以保持事件状态。
这会使用 .watchPosition()
每 15 秒检查一次位置,并在五秒后使用 .clearWatch()
停止检查。
演示:https://jsfiddle.net/ThinkingStiff/phabq6r3/
脚本:
var latitude, longitude, accuracy;
function setGeolocation() {
var geolocation = window.navigator.geolocation.watchPosition(
function ( position ) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
accuracy = position.coords.accuracy;
document.getElementById( 'result' ).innerHTML +=
'lat: ' + latitude + ', '
+ 'lng: ' + longitude + ', '
+ 'accuracy: ' + accuracy + '<br />';
},
function () { /*error*/ }, {
maximumAge: 250,
enableHighAccuracy: true
}
);
window.setTimeout( function () {
window.navigator.geolocation.clearWatch( geolocation )
},
5000 //stop checking after 5 seconds
);
};
setGeolocation();
window.setInterval( function () {
setGeolocation();
},
15000 //check every 15 seconds
);
HTML:
<div id="result"></div>
关于javascript - geolocation.watchPosition 打破 geolocation.getCurrentPosition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8720334/