Reputation: 12391
I'd like to create an application, what is showing my current position on a google map in "real time".
Here is the relevant code:
function updatePosition() {
navigator.geolocation.getCurrentPosition(function (position) {
var myLatLng = {lat: position.coords.latitude, lng: position.coords.longitude};
marker.setPosition(myLatLng);
$('#log').append('<p>new position - lat: ' + position.coords.latitude + ', lng: ' + position.coords.longitude + ' </p>');
});
}
setInterval(updatePosition, 2000);
How can I say it... It works. But not as I expected. Instead 2secs, it refreshes my position and write into the log about 5 - 30 secs.
Is it possible to do this position refreshing with google maps, or if not, should I use another map like Leaflet or OpenLayers?
Upvotes: 1
Views: 860
Reputation: 1
If you run code like this
function updatePosition() {
navigator.geolocation.getCurrentPosition(function (position) {
var myLatLng = {lat: position.coords.latitude, lng: position.coords.longitude};
console.log(myLatLng);
setTimeout(updatePosition, 0);
});
}
updatePosition();
You'll see that the getCurrentPosition takes a finite amount of time - in my case, 5 seconds, that's with a ZERO timeout ... so, running it every two seconds like you are is not going to make it update any faster
Upvotes: 1
Reputation: 2423
The delay you are encountering is probably due to the delay to acquire the position from the device.
Moreover, try checking for errors as a second handler to the getCurrentPosition
function.
Upvotes: 0