Search code examples
javascripthtmlgeolocationnavigator

Geo-Location Custom Update Interval (30 seconds)


I have a geo-location checking mobile application (for route tracking) and I need to be able to specify a custom temporal interval for location updates that can be modified by the user. I am using the watchPosition() function as accuracy is important and getCurrentPosition() does not seem to work very well. However, I still want the user to be able to customize the update interval depending on their preferences.

Here is a rough representation of my code so far: http://jsfiddle.net/ppyordanov/taz4g5t0/5/ .

html:

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

JS:

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
        } 
    );

};

setGeolocation();

window.setTimeout( function () {
        setGeolocation();
    }, 
    30000 //check every 30 seconds
);

I can use setTimeout() to manipulate the time interval, but it does not seem to have any effect on the output. It keeps updating about once every second. How can I increase that to 30 seconds?


Solution

  • Instead of calling setGeolocation(); every n seconds, I save the location in the window.navigator.geolocation.watchPosition() call and then update it in a separate function via the setInterval() function.