Juan Antonio Orozco Juan Antonio Orozco - 1 year ago 116
Javascript Question

geolocation.watchPosition breaks geolocation.getCurrentPosition

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

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

For this I intended to use
. 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
. 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 Source

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/


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


window.setInterval( function () {
    15000 //check every 15 seconds


<div id="result"></div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download