forked from gregsramblings/getAccurateCurrentPosition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geo.js
47 lines (39 loc) · 1.83 KB
/
geo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
};