-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.geolocation.js
68 lines (65 loc) · 1.86 KB
/
jquery.geolocation.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* jQuery Geolocation helper v@VERSION
* https://github.com/sash/jquery-geolocation
*
* Copyright 2011 Alexander (SASh) Alexiev
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Date: @DATE
*/
(function(jQuery,undefined){
// Does the same as navigator.geolocation.getCurrentPosition
// except when minAccuracy option is provided.
// In the latter case the timeout option is required (and if missing is assumed to be 10 seconds) and
// navigator.geolocation.watchPosition is used to wait for accurate enough position before
// triggering the success or error callbacks
jQuery.getCurrentPosition = function(success, fail, options){
fail = fail || function(){};
success = success || function(){};
options = options || {};
if (navigator.geolocation) {
if (typeof options.minAccuracy != undefined){
var timeout = options.timeout || 10000;
var minAccuracy = options.minAccuracy;
var watchPos=null;
var best=null;
var cancel = function(){
if (watchPos!=null){
navigator.geolocation.clearWatch(watchPos);
watchPos=null;
return true;
}
return false;
}
watchPos = navigator.geolocation.watchPosition(function(position){
if (position.coords.accuracy<=minAccuracy){
best = null;
cancel();
success(position);
}
else{
if (best == null || best.coords.accuracy > position.coords.accuracy){
best = position;
}
}
}, function(message){
cancel();
if (best!=null) success(best);
else fail(message);
}, options);
setTimeout(function(){
if (cancel()){
if (best!=null) success(best);
else fail({'message':'timeout'});
}
}, timeout);
}
else{
navigator.geolocation.getCurrentPosition(success,fail,options);
}
} else {
fail({'message': 'not supported'});
}
}
})(jQuery);