Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gorelog/1436289 to your computer and use it in GitHub Desktop.
Save gorelog/1436289 to your computer and use it in GitHub Desktop.
navigator.geolocation.getAccuratePosition
// Sligntly modified to return the best position out of those generated. The original script (https://gist.github.com/510278/)
// only returned the last one. tmpAccuracy was added to check against the current position and set the bestPosition if indeed it is the best.
//
// navigator.geolocation.getAccuratePosition() is an improved version of navigator.geolocation.getCurrentPosition()
//
// getAccuratePosition() is designed and tested for iOS.
//
// The problem with getCurrentPosition() is that it returns an inaccurate position even with "enableHighAccuracy" enabled.
// The problem with watchPosition() is that it calls the success handler every second, and it is resource-intensive.
//
// getAccuratePosition() calls the callback only once, but uses watchLocation() internally to obtain a position that meets your accuracy needs.
// If the timeout is exceeded before a position meeting your accuracy is needed, the best position is returned to the
// success callback, and the error callback does not fire. If you really care about accuracy, you should check it
// yourself in your success callback.
//
// getAccuratePosition() has the same signature as getCurrentPosition() and watchPosition()
// (see http://dev.w3.org/geo/api/spec-source.html#get-current-position)
// BUT allows specification of opts.accuracy, which is treated as a minium required accuracy (in meters)
// If no accuracy is specified, it defaults to 1000m if enableHighAccuracy=false, else 50m.
navigator.geolocation.getAccuratePosition = function(successF, errorF, opts)
{
opts.accuracy = opts.accuracy || (opts.enableHighAccuracy ? 50 : 1000);
opts.timeout = opts.timeout || 10;
var watcher;
var bestPosition = {};
var initialTimeMS = (new Date()).getTime();
var tmpAccuracy = 99999;
var mySuccessF = function(position) {
//console.log('watchPosition update: ' + $.toJSON(position));
console.log('watchPosition update: ' + JSON.stringify(position));
// Get the best position out of any of those generated
if (position.coords.accuracy <= tmpAccuracy)
{
tmpAccuracy = position.coords.accuracy;
bestPosition = position;
}
if (position.coords.accuracy <= opts.accuracy || ((new Date()).getTime() - initialTimeMS) > opts.timeout)
{
navigator.geolocation.clearWatch(watcher);
successF(bestPosition);
}
};
var myErrorF = function(error) {
navigator.geolocation.clearWatch(watcher);
errorF(error);
};
watcher = navigator.geolocation.watchPosition(mySuccessF, myErrorF, opts);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment