SiteKickr Web Development

Browser based geolocation – the accuracy question

I seem to be working on a lot of location-based apps lately, so I apologize if I'm leaning too heavily on this subject. It's pretty cool though, if you think about it, to be able to grab a user's location through JavaScript and use it in your web application. No doubt the original HTML spec authors, nor the browser makers from the 90's never saw this coming.

Not only are we able to get the user's latitude and longitude through the JavaScript GeoLocation API, but we can specify the level of accuracy that our app requires. Why wouldn't we always want the highest accuracy possible? Because higher accuracy requires the use of GPS, which consumes a good deal of power, draining battery life quicker.

There are tons of articles out there that speak to the differences and reasons to use low or high accuracy, so I'll skip it.
 

GeoLocation Fallback to Low Accuracy

What I'd like to do is talk about what happened during the latest round of testing on one of our apps. High accuracy is preferred in our application, though we could probably get away without it. Given that, we chose to set the enableHighAccuracy parameter to true.

This was working great in all of our desktop and mobile tests, until one day, one of our testers got a failure response from the JavaScript's GeoLocation module. There wasn't a clear reason for this failure, but not only was a high accuracy response unavailable, it didn't even return a low accuracy response.

So, this brought us to the conclusion that it's important to check for both levels of accuracy. That is, if a high-accuracy call fails, perform a separate low-accuracy call. This seemed to produce a far more consistent return of coordinates over relying on the device itself to fallback to low accuracy.

Instead of making you figure out the code for yourself, here's a little snippet I came up with:

 

function getGeoLocation(callback) {
    navigator.geolocation.getCurrentPosition(
        callback,
        function (error) {
            if (error.code === 1) {
                alert ('You have denied access to your location.');
                return false;
            }
           
            navigator.geolocation.getCurrentPosition(
                callback,
                function(error) {
                    alert ('Your location could not be determined.');
                },
                { enableHighAccuracy: false, timeout: 8000, maximumAge: 60000 }
            );
        },
        { enableHighAccuracy: true, timeout: 8000, maximumAge: 60000 }
    );   
}

 

Using the getGeoLocation function:

getGeoLocation( function (position) {

    alert ('Your location: ' + position.coords.latitude + ', ' + position.coords.longitude);

});