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".
The getCurrentPosition method retrieves the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The location information is returned in a Position object.
The Geolocation method watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function.
If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users. location will no longer function.
The watchPosition method returns a unique transaction ID (number) associated with the asynchronous call. Use this ID to cancel the watchPosition call and to stop receiving location updates.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With