On a mobile device, .getCurrentPosition() very inaccurate. Using .watchPosition() more accurate, but it takes about five seconds to get a better reading. After that, the battery discharges to support it.
This checks the position every 15 seconds with .watchPosition() and stops checking after five seconds with .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>
ThinkingStiff
source share