Juan Antonio Orozco Juan Antonio Orozco - 16 days ago 9
Javascript Question

geolocation.watchPosition breaks geolocation.getCurrentPosition

I'm working on a web app with google maps and using

getCurrentPosition()
to get the user position. That works fine but I need to track user position over time.

For this I intended to use
watchPosition()
. Acording to the API reference API reference it must immediatly execute data acquisition and execute the callback, but it doesn't. Instead it freezes, and I can no longer use
getCurrentPosition()
. I have been searching for a cause for this and I cant figure out why is behaving that way. I'm using the latest Chrome for Linux Mint "Lisa".

Answer

On a mobile device, .getCurrentPosition() is very inaccurate. Using .watchPosition() is more accurate, but it takes about five seconds to get the best reading. After that, it wastes battery to keep it active.

This checks the position every 15 seconds using .watchPosition() and stops checking after five seconds using .clearWatch().

Demo: https://jsfiddle.net/ThinkingStiff/phabq6r3/

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.setInterval( function () {
        setGeolocation();
    }, 
    15000 //check every 15 seconds
);

HTML:

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