我有一个地理位置检查移动应用程序(用于路线跟踪),我需要能够为位置更新指定可由用户修改的自定义时间间隔。我使用 watchPosition() 函数,因为准确性很重要,而 getCurrentPosition() 似乎工作得不太好。不过,我仍然希望用户能够根据自己的喜好自定义更新间隔。
这是迄今为止我的代码的粗略表示:http://jsfiddle.net/ppyordanov/taz4g5t0/5/ .
html:
<div id="result"></div>
JS:
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
}
);
};
setGeolocation();
window.setTimeout( function () {
setGeolocation();
},
30000 //check every 30 seconds
);
我可以使用setTimeout()来操纵时间间隔,但它似乎对输出没有任何影响。它大约每秒更新一次。如何将其增加到 30 秒?
最佳答案
我不是每 n
秒调用 setGeolocation();
,而是将位置保存在 window.navigator.geolocation.watchPosition()
调用,然后通过 setInterval()
函数在单独的函数中更新它。
关于javascript - 地理位置自定义更新间隔(30 秒),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27460264/