Part of the new geolocation api provides a method to get a user’s current position. In theory that’s awesome, but in practice it was returning inconsistent results. Sometimes it was accurate, other times it was off by miles. If I tried it multiple times in a row it would get more accurate, but only some of the time. The app I was working on needed better accuracy, so I tried a few things.

First I tried specifying the precision parameter (by default it is set to low precision):

navigator.geolocation.getCurrentPosition(centerMap, centerMap, {enableHighAccuracy:true, maximumAge:0, timeout:30000});

This was MUCH more accurate, but it took about 45 seconds on my iphone to respond. Not okay. I looked to another solution: watchPosition(). It basically calls getCurrentPosition() multiple times so it can narrow in on where you are if you’re moving.


Boom. Much better results. BUT it’s being called a lot, and I don’t want my map jumping around, I just want 1 accurate reading. I came up with the following solution:

var watchCount = 0;

var watchId = navigator.geolocation.watchPosition(centerMap); 

function centerMap(location)
var myLatlng = new google.maps.LatLng(location.coords.latitude,location.coords.longitude);

//do it 2 times

//show current location on map
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: ‘‘,
clickable: false,
//don’t need to watch anymore

Basically it starts watchPosition until 2 positions are returned (I mentioned earlier how the 2nd result is always more accurate than the first), then it stops following the user. I set the threshold to 2 because the success callback is only called when there is a change in¬†location, so if I had set it higher and the user wasn’t moving I wouldn’t get what I want.

Check out the spec for more info!

  One Response to “Even better geolocation than getPosition() with modified watchPosition()”

  1. You can use “if (position.coords.accuracy <= 50) " then unwatch it.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



© 2012 ShaneLabs Suffusion theme by Sayontan Sinha