|
// 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 mySuccessF = function(position) { |
|
console.log('watchPosition update: ' + $.toJSON(position)); |
|
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); |
|
}; |
Hello,
I want to thank you for sharing this. I've been struggling to get accurate positioning and I'm hoping this will help. I noticed that the bestPosition returned was always the last one generated, so I added a little check before passing the current position to the bestPosition. https://gist.github.com/1436289
Thanks again.