-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocation-service.js
89 lines (73 loc) · 2.03 KB
/
location-service.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var MicroEvent = require('microevent')
var GeoUtil = require('./util/geo-util.js')
var STATES = {
stopped: 0,
unavailable: 1,
acquiring: 2,
started: 3,
denied: 4
}
var ACCURATE_MAX = 100
var LOCATION_MAX_AGE = 10000
function LocationService (provider) {
this.provider = provider
this._location = undefined
this._state = STATES.stopped
this.hasAccurateLocation = false
}
module.exports = LocationService
MicroEvent.mixin(LocationService)
LocationService.States = STATES
Object.defineProperty(LocationService.prototype, 'location', {
get: function () {
return this._location
},
set: function (location) {
var oldLocation = this._location
this._location = location
if (!oldLocation || !oldLocation.equals(location)) {
this.trigger('change:location', location, oldLocation)
}
this.hasAccurateLocation = (location && location.accuracy <= ACCURATE_MAX)
if (location) {
this.state = STATES.started
}
}
})
Object.defineProperty(LocationService.prototype, 'state', {
get: function () {
return this._state
},
set: function (state) {
var oldState = this._state
this._state = state
if (oldState !== state) {
this.trigger('change:state', state)
}
}
})
LocationService.prototype.start = function () {
this.state = STATES.acquiring
this.provider.start(
this._onLocation.bind(this),
this._onError.bind(this)
)
}
LocationService.prototype.pause = function () {
this.provider.stop()
this._location = undefined
this._state = STATES.stopped
}
LocationService.prototype._onLocation = function (location) {
if (this._shouldSetLocation(location)) {
this.location = location
}
}
LocationService.prototype._onError = function (error) {
this.state = (error.code === 1) ? STATES.denied : STATES.unavailable
}
LocationService.prototype._shouldSetLocation = function (loc) {
return (loc.timestamp >= Date.now() - LOCATION_MAX_AGE &&
(!this.location || (loc.accuracy <= this.location.accuracy ||
GeoUtil.distance(this.location, loc) > loc.accuracy)))
}