Skip to content

Instantly share code, notes, and snippets.

@niczak
Created July 25, 2016 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niczak/8aac7ea4e086404477b3aa081d00222b to your computer and use it in GitHub Desktop.
Save niczak/8aac7ea4e086404477b3aa081d00222b to your computer and use it in GitHub Desktop.
navigator.geolocation.getAccurateCurrentPosition = function (geolocationSuccess, geolocationError, geoprogress, options) {
var lastCheckedPosition,
locationEventCount = 0,
watchID,
timerID;
options = options || {};
var checkLocation = function (position) {
lastCheckedPosition = position;
locationEventCount = locationEventCount + 1;
// We ignore the first event unless it's the only one received because some devices seem to send a cached
// location even when maxaimumAge is set to zero
if ((position.coords.accuracy <= options.desiredAccuracy) && (locationEventCount > 1)) {
clearTimeout(timerID);
navigator.geolocation.clearWatch(watchID);
foundPosition(position);
} else {
geoprogress(position);
}
};
var stopTrying = function () {
navigator.geolocation.clearWatch(watchID);
foundPosition(lastCheckedPosition);
};
var onError = function (error) {
clearTimeout(timerID);
navigator.geolocation.clearWatch(watchID);
geolocationError(error);
};
var foundPosition = function (position) {
geolocationSuccess(position);
};
if (!options.maxWait) options.maxWait = 10000; // Default 10 seconds
if (!options.desiredAccuracy) options.desiredAccuracy = 20; // Default 20 meters
if (!options.timeout) options.timeout = options.maxWait; // Default to maxWait
options.maximumAge = 0; // Force current locations only
options.enableHighAccuracy = true; // Force high accuracy (otherwise, why are you using this function?)
watchID = navigator.geolocation.watchPosition(checkLocation, onError, options);
timerID = setTimeout(stopTrying, options.maxWait); // Set a timeout that will abandon the location loop
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment