/
location-tracker.ts
71 lines (54 loc) · 1.71 KB
/
location-tracker.ts
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
import {Injectable, NgZone} from '@angular/core';
import {BackgroundGeolocation, BackgroundGeolocationConfig} from '@ionic-native/background-geolocation';
import { Geolocation, Geoposition } from '@ionic-native/geolocation';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
@Injectable()
export class LocationTrackerProvider {
public watch: any;
public lat: number = 0;
public lng: number = 0;
constructor(
public zone: NgZone,
public backgroundGeolocation: BackgroundGeolocation,
public geolocation: Geolocation
) {
}
public startTracking() {
let config : BackgroundGeolocationConfig = {
desiredAccuracy: 0,
stationaryRadius: 20,
distanceFilter: 10,
debug: true,
interval: 2000
};
this.backgroundGeolocation.configure(config).subscribe((location) => {
console.log('BackgroundGeolocation: ' + location.latitude + ',' + location.longitude);
// Update inside of Angular's zone
this.zone.run(() => {
this.lat = location.latitude;
this.lng = location.longitude;
});
}, (err) => {
console.log(err);
});
this.backgroundGeolocation.start();
// Background tracking
let options = {
frequency: 3000,
enableHighAccuracy: true
};
this.watch = this.geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {
console.log(position);
this.zone.run(() => {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
});
});
}
public stopTracking() {
console.log('stopTracking');
this.backgroundGeolocation.finish();
this.watch.unsubscribe();
}
}