Geolocation.watchPosition breaks geolocation.getCurrentPosition

I am working on a google maps web application and using getCurrentPosition() to get the user's position. This works fine, but I need to track the user's position over time.

For this, I intended to use watchPosition() . According to the API API reference link, it should immediately collect data and execute a callback, but that is not the case. Instead, it freezes, and I can no longer use getCurrentPosition() . I was looking for the reason for this, and I can’t understand why it behaves this way. I am using the latest version of Chrome for Linux Mint "Lisa".

+8
javascript html5 geolocation
source share
1 answer

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> 
+14
source share

All Articles