How to get HTML5 position in WebView updated at a regular interval (with FINE_ACCURACY)

时光总嘲笑我的痴心妄想 提交于 2019-12-06 00:52:32

I've found that phones (at least with iPhones) usually need three checks to get an accurate reading, almost as if they are triangulating the position. The problem, as you have discovered, is that each new call to getCurrentPosition() seems to start "blind", so it doesn't get any more accurate (results vary when you're running this function on a desktop/laptop).

The solution is geolocation.watchPosition(). That function uses previous calls to improve accuracy. After about five seconds, it's as accurate as it's going to get (if you're not moving), so you stop checking. Also, it will stop checking any time it thinks it won't get any more accurate. Use window.setTimeout() to control the interval.

Demo: http://jsfiddle.net/ThinkingStiff/yn3Bq/

HTML:

<div id="result"></div>

Script:

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.setTimeout( function () {
        setGeolocation();
    }, 
    30000 //check every 30 seconds
);

Output:

lat: 35.5830119, lng: -124.4871223, accuracy: 40
lat: 35.5829974, lng: -124.4871525, accuracy: 30

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!