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.

navigator.geolocation.watchPosition(centerMap);

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);
map.setCenter(myLatlng);
map.setZoom(17);
watchCount++;

//do it 2 times
if(watchCount>=2)
{

//show current location on map
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: ‘http://www.google.com/gmm/images/blue_dot_circle.png‘,
clickable: false,
zIndex:1
});
//don’t need to watch anymore
navigator.geolocation.clearWatch(watchId);
}
}

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!

About Shane
Shane is the creator of Page Speed Analytics tool MachMetrics. You can follow his entrepreneurial activities on his blog SideProjectProfit

  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>

(required)

(required)

   
© 2012 ShaneLabs Suffusion theme by Sayontan Sinha