gpt4 book ai didi

javascript - 地理定位 watch 不会持续触发

转载 作者:行者123 更新时间:2023-11-30 05:30:16 24 4
gpt4 key购买 nike

我有一个测试应用程序可以从 HTML5 地理定位服务中获取纬度/经度值。不幸的是,它以相当不一致的时间间隔触发,从 500 毫秒到 10000 毫秒不等。我试过更改 watch 的 maximimAge 和超时参数,但这些参数似乎没有任何改变。我正在 Chrome 中以及通过 Android Lollipop 构建上的简单 Cordova 应用程序对其进行测试。下面的代码只是显示 watch 的时间戳值,以消除可能导致问题的任何其他延迟。看起来间隔接近 1 秒然后 5 秒的重复模式。我还尝试将地理位置提取函数放在 setInterval 函数中,它的行为具有相同的 1 秒和 5 秒重复间隔。

<html>
<body>
<h1>Timestamp</h1>
<div id="mytimestamp"></div>
<button id="btnstopwatch">Stop GPS</button>
</body>
</html>

<script type="text/javascript">
var mytimestamp = document.getElementById("mytimestamp");
//start watching location
watchPositionId = navigator.geolocation.watchPosition(updateCompass,handleerror,{
enableHighAccuracy:true,
maximumAge:3000,
timeout:3000
});

function updateCompass(p)
{
mytimestamp.innerHTML = p.timestamp;
}

function handleerror(err)
{
if(err.code ==1)
{
//user said no
alert('Please allow access to GPS');
}
else
{
alert(err.code);
}
}
</script>

最佳答案

关于watchPosition(),在下面link w3 说“仅在获得新位置时调用 successCallback ......实现可能会对回调频率施加限制,以避免无意中消耗不成比例的资源量。”

这意味着 watchPosition() 正在等待会导致位置发生变化的事件,否则它什么都不做。所以 watchPosition() 不会调用 updateCompass() 除非它看到位置的变化。另外,关于watchPosition(),maximumAgetimeout参数与获取新位置有关,这些参数与watchPosition()的次数和时间无关被称为...

WatchPosition() 防止连续调用以查看位置是否发生变化,并且仅在与位置变化相关的某些事件发生时才使用react,这有助于节省电池等资源。但是如果你真的想看到位置,假设每三秒一次,无论位置是否改变,我认为设置一个时间间隔将是一个很好的方法。

var watchPositionId;
//start watching location
setInterval(function () {
watchPositionId = navigator.geolocation.watchPosition(updateCompass, handleerror, {
enableHighAccuracy: true,
maximumAge: 3000,
timeout: 3000
});
}, 3000);

function updateCompass(p) {
mytimestamp.innerHTML = p.timestamp;
// if you have alert message it will counts seconds once you dismiss the alert,
//this may be part of the issue why you kept getting diffrent intervals.
//alert(p.timestamp);
navigator.geolocation.clearWatch(watchPositionId);
}

你提到你尝试过 setInterval 但它没有用,所以请注意我在上面的代码中注释了 alert() 因为它导致我有延迟,没有它,html 中的时间戳每 3000 毫秒更新一次精度约5ms。

如果您想使用 watchPosition(),则上述方法有效,因为 clearWatch() 会停止 watchPosition() 并进一步回调。基本上,上面的代码每三秒启动一次新的 watchPosition() 并用 clearWatch() 终止它。也就是说,我认为 watchPosition() 不是这种方法中使用的最佳方法,除非您预计在此时间间隔内位置会发生重大变化。我宁愿使用 getCurrentPosition(),因为它可以完成工作并且不等待位置的变化。

 var watchPositionId;
//start watching location
setInterval(function () {
watchPositionId = navigator.geolocation.getCurrentPosition(updateCompass, handleerror, {
enableHighAccuracy: true,
maximumAge: 3000,
timeout: 3000
});
}, 3000);

function updateCompass(p) {
mytimestamp.innerHTML = p.timestamp;
}

关于javascript - 地理定位 watch 不会持续触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31764217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com