gpt4 book ai didi

javascript - 如何运行 Geolocation watchPosition 直到获得准确的结果?

转载 作者:行者123 更新时间:2023-12-02 14:06:39 26 4
gpt4 key购买 nike

我一直在使用地理位置 navigator.geolocation.getCurrentPosition但发现不如 navigator.geolocation.watchPosition 准确。所以我的想法是让运行navigator.geolocation.watchPosition直到准确度达到 <=100然后显示位置,如果15秒内失败则报错。

这是我得到的:

function getLocation() {
if (navigator.geolocation) {
var geo_options = {
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 0
};
var watchID = navigator.geolocation.watchPosition(
showPosition,
showError,
geo_options
);
} else {
// Error here. Geolocation disabled.
}
}

function showPosition(position) {
if (position.coords.accuracy > 100) {
// Keep trying
} else {
// Fire up the map, we got a position!
// Clear the watchID.
navigator.geolocation.clearWatch(watchID);
}
}

我的问题是,由于某种原因,我无法在成功时清除 watchID,因为它说它是未定义的。我猜那是因为该函数位于外部。

有没有一种简单的方法可以做到这一点,以便 showPosition仅当准确度低于 100 时才触发?现在showPosition随时会被触发,因为它位于 watchPosition 内功能。

最佳答案

那是因为 watchID 未定义。您已将其定义在 getLocation 范围内,该范围不与 showPosition 共享其范围。尝试在它们之外声明它。

var watchID;

function getLocation() {
...
watchID = navigator.geolocation.watchPosition(showPosition, showError, geo_options);
}

function showPosition(position) {
if (position.coords.accuracy <= 100) {
navigator.geolocation.clearWatch(watchID);
}
}

专业提示:如果您的代码在 strict mode 中运行它会提醒您此错误。

'use strict';

function declareX() {
var x = 1;
}

function useX() {
console.log(x);
}

declareX();
useX();

关于javascript - 如何运行 Geolocation watchPosition 直到获得准确的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987253/

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