geolocation.watchPosition打破geolocation.getCurrentPosition

时间:2012-01-03 23:53:26

标签: javascript html5 geolocation

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

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

1 个答案:

答案 0 :(得分:14)

在移动设备上,.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>
相关问题