javascript - geolocation.watchPosition 打破 geolocation.getCurrentPosition

标签 javascript html geolocation

我正在开发一个带有谷歌地图的网络应用程序,并使用 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/

相关文章:

javascript - 使用此代码在游戏中循环音频,但它不起作用。为什么?

php - 在帖子内容的第一个 h2 标签之前插入广告

Python UnicodeEncodeError : 'charmap' codec can't encode when using GEOPY

android - 我正在尝试安排 ionic Cordova 背景地理定位插件。这可能吗?

python - 使用IP地址在python中查找位置

javascript - 我有一个链式下拉框,同时提醒第二个下拉框我也在第一个框上收到警报

javascript - ASP.NET MVC : GET params not properly deserialized

c# - 从客户端脚本调用代码隐藏中的方法

javascript - SVG 曲线上的动画选取框

html - 在父鼠标悬停时更改子样式,使用 :after