geolocation.watchPosition打破geolocation.getCurrentPosition

Jua*_*zco 8 javascript html5 geolocation

我正在开发一个带谷歌地图的网络应用程序,getCurrentPosition()用于获取用户位置.这很好,但我需要跟踪用户的位置.

为此,我打算使用watchPosition().根据API参考API参考,它必须立即执行数据采集并执行回调,但事实并非如此.相反,它冻结,我不能再使用了getCurrentPosition().我一直在寻找原因,我无法弄清楚为什么这样做.我正在使用最新的Chrome for Linux Mint"Lisa".

Thi*_*iff 14

在移动设备上,.getCurrentPosition()非常不准确.使用.watchPosition()更准确,但获得最佳读数需要大约五秒钟.在那之后,它浪费电池以保持活跃.

这将每隔15秒检查一次位置,.watchPosition()并在五秒钟后停止检查.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
);
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="result"></div>
Run Code Online (Sandbox Code Playgroud)

  • 这个脚本完全荒谬.在脚本加载时调用watchPosition,在没有任何原因的情况下在15秒后调用第二次.当然setTimeout不会每15秒调用一次setGeolocation,而且你不必这样做.如果用户的位置实际发生变化,则给予watchPosition的第一个函数将获得回调.5秒后调用clearWatch也毫无意义. (6认同)