forked from transistorsoft/capacitor-background-geolocation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadvanced.page.ts
1186 lines (1048 loc) · 34 KB
/
advanced.page.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Component,
ViewChild,
ElementRef,
OnInit,
NgZone,
AfterContentInit
} from '@angular/core';
import { Router} from '@angular/router';
import {
AlertController,
Platform,
ModalController,
LoadingController
} from '@ionic/angular';
import BackgroundGeolocation, {
State,
Location,
Geofence,
HttpEvent,
MotionActivityEvent,
ProviderChangeEvent,
MotionChangeEvent,
GeofenceEvent,
GeofencesChangeEvent,
HeartbeatEvent,
ConnectivityChangeEvent,
TransistorAuthorizationToken
} from "../capacitor-background-geolocation";
import {ENV} from "../ENV";
import {ICON_MAP} from "../lib/icon-map";
import {COLORS} from "../lib/colors";
import {LongPress} from "./lib/LongPress";
import {BGService} from './lib/BGService';
import {SettingsService} from './lib/SettingsService';
import {registerTransistorAuthorizationListener} from "../lib/authorization";
import { SettingsPage } from './modals/settings/settings.page';
import { GeofencePage} from "./modals/geofence/geofence.page";
declare var google;
const CONTAINER_BORDER_POWER_SAVE_OFF = 'none';
const CONTAINER_BORDER_POWER_SAVE_ON = '7px solid red';
// Messages
const MESSAGE = {
reset_odometer_success: 'Reset odometer success',
reset_odometer_failure: 'Failed to reset odometer: {result}',
sync_success: 'Sync success ({result} records)',
sync_failure: 'Sync error: {result}',
destroy_locations_success: 'Destroy locations success ({result} records)',
destroy_locations_failure: 'Destroy locations error: {result}',
removing_markers: 'Removing markers...',
rendering_markers: 'Rendering markers...'
}
@Component({
selector: 'app-advanced',
templateUrl: './advanced.page.html',
styleUrls: ['./advanced.page.scss'],
})
export class AdvancedPage implements OnInit, AfterContentInit {
@ViewChild('map', {static: true}) private mapElement: ElementRef;
/**
* @property {google.Map} Reference to Google Map instance
*/
map: any;
/**
* @property {Object} state
*/
state: any;
/**
* @property {boolean}
*/
enabled: boolean;
/**
* @property {Object} lastLocation
*/
lastLocation: any;
/**
* @property {Object} map of icons
*/
iconMap: any;
currentLocationMarker: any;
locationAccuracyCircle: any;
geofenceHitMarkers: any;
polyline: any;
stationaryRadiusCircle: any;
geofenceCursor: any;
locationMarkers: any;
geofenceMarkers: any;
lastDirectionChangeLocation: any;
// Geofence Hits
geofenceHits: any;
// FAB Menu
isMainMenuOpen: boolean;
isSyncing: boolean;
isDestroyingLocations: boolean;
isResettingOdometer: boolean;
isEmailingLog: boolean;
isMapMenuOpen: boolean;
isWatchingPosition: boolean;
// Private
testModeClicks: number;
testModeTimer: any;
constructor(
private alertCtrl:AlertController,
private router:Router,
private modalController:ModalController,
private loadingCtrl: LoadingController,
private bgService: BGService,
private settingsService: SettingsService,
private zone: NgZone,
private platform:Platform) {
// FAB Menu state.
this.isMainMenuOpen = false;
this.isMapMenuOpen = false;
this.isSyncing = false;
this.isResettingOdometer = false;
this.isEmailingLog = false;
this.isWatchingPosition = false;
this.testModeClicks = 0;
this.iconMap = ICON_MAP;
this.geofenceHits = [];
// Initial state
this.state = {
enabled: false,
isMoving: false,
geofenceProximityRadius: 1000,
trackingMode: 1,
isChangingPace: false,
activityIcon: this.iconMap['activity_unknown'],
odometer: 0,
provider: {
gps: true,
network: true,
enabled: true,
status: -1
},
containerBorder: 'none'
};
/// Listen to PAUSE/RESUME events for fun.
this.platform.pause.subscribe(() => {
console.log('************************** PAUSE');
});
this.platform.resume.subscribe(() => {
console.log('************************** RESUME');
})
}
async ionViewWillEnter() {
console.log('⚙️ ionViewWillEnter');
}
async ngAfterContentInit() {
console.log('⚙️ ngAfterContentInit');
// Setup the GoogleMap
await this.configureMap();
// When live-reloading, we need to tell the plugin to remove all its listeners otherwise new listeners
// are accumulated with each live-reload.
await BackgroundGeolocation.removeListeners();
// Re-register Transistor Demo Server Authorization listener.
registerTransistorAuthorizationListener(this.router);
// Configure the plugin.
this.configureBackgroundGeolocation();
}
ngOnInit() {}
/**
* Configure BackgroundGeolocation plugin
*/
async configureBackgroundGeolocation() {
// [optional] We first bind all our event-handlers to *this* so that we have the option to later remove these
// listeners with BackgroundGeolocation.un("eventname", this.onMyHandler), since the #bind method returns a new function instance.
// To remove an event-handler requires a reference to the *exact* success-callback provided to #on
// eg:
// this.onLocation = this.onLocation.bind(this);
// BackgroundGeolocation.onLocation(this.onLocation); <-- add listener
// BackgroundGeolocation.un("location", this.onLocation); <-- remove listener
// If you don't plan to remove events, this is unnecessary.
//
this.onLocation = this.onLocation.bind(this);
this.onLocationError = this.onLocationError.bind(this);
this.onMotionChange = this.onMotionChange.bind(this);
this.onHeartbeat = this.onHeartbeat.bind(this);
this.onGeofence = this.onGeofence.bind(this);
this.onActivityChange = this.onActivityChange.bind(this);
this.onProviderChange = this.onProviderChange.bind(this);
this.onGeofencesChange = this.onGeofencesChange.bind(this);
this.onSchedule = this.onSchedule.bind(this);
this.onHttp = this.onHttp.bind(this);
this.onPowerSaveChange = this.onPowerSaveChange.bind(this);
this.onConnectivityChange = this.onConnectivityChange.bind(this);
this.onEnabledChange = this.onEnabledChange.bind(this);
// Listen to BackgroundGeolocation events
BackgroundGeolocation.onLocation(this.onLocation, this.onLocationError);
BackgroundGeolocation.onMotionChange(this.onMotionChange);
BackgroundGeolocation.onHeartbeat(this.onHeartbeat);
BackgroundGeolocation.onGeofence(this.onGeofence);
BackgroundGeolocation.onActivityChange(this.onActivityChange);
BackgroundGeolocation.onProviderChange(this.onProviderChange);
BackgroundGeolocation.onGeofencesChange(this.onGeofencesChange);
BackgroundGeolocation.onSchedule(this.onSchedule);
BackgroundGeolocation.onHttp(this.onHttp);
BackgroundGeolocation.onPowerSaveChange(this.onPowerSaveChange);
BackgroundGeolocation.onConnectivityChange(this.onConnectivityChange);
BackgroundGeolocation.onEnabledChange(this.onEnabledChange);
BackgroundGeolocation.onNotificationAction(this.onNotificationAction);
/// A Big red border is rendered around view when the device is in "Power Saving Mode".
this.state.containerBorder = (await BackgroundGeolocation.isPowerSaveMode()) ? CONTAINER_BORDER_POWER_SAVE_ON : CONTAINER_BORDER_POWER_SAVE_OFF;
const localStorage = (<any>window).localStorage;
const orgname = localStorage.getItem('orgname') || ''
const username = localStorage.getItem('username') || '';
let token:TransistorAuthorizationToken = await
BackgroundGeolocation.findOrCreateTransistorAuthorizationToken(orgname, username,ENV.TRACKER_HOST);
// With the plugin's #ready method, the supplied config object will only be applied with the first
// boot of your application. The plugin persists the configuration you apply to it. Each boot thereafter,
// the plugin will automatically apply the last known configuration.
BackgroundGeolocation.ready({
transistorAuthorizationToken: token,
reset: false,
debug: true,
locationAuthorizationRequest: 'Always',
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
backgroundPermissionRationale: {
title: "Allow {applicationName} to access this device's location even when closed or not in use.",
message: "This app collects location data to enable recording your trips to work and calculate distance-travelled.",
positiveAction: 'Change to "{backgroundPermissionOptionLabel}"',
negativeAction: 'Cancel'
},
distanceFilter: 10,
stopTimeout: 1,
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true,
autoSync: true,
maxDaysToPersist: 14,
}).then(async (state) => {
// Store the plugin state onto ourself for convenience.
console.log('- BackgroundGeolocation is ready: ', state);
this.zone.run(() => {
this.state.enabled = state.enabled;
this.state.isMoving = state.isMoving;
this.state.geofenceProximityRadius = state.geofenceProximityRadius;
this.state.trackingMode = state.trackingMode;
if ((state.schedule.length > 0)) {
BackgroundGeolocation.startSchedule();
}
});
}).catch((error) => {
console.warn('- BackgroundGeolocation configuration error: ', error);
});
}
/**
* Configure Google Maps
*/
configureMap() {
return new Promise((resolve:Function) => {
// Handle case where app booted without network accesss (google maps lib fails to load)
if (typeof(google) !== 'object') {
console.warn('- map not loaded');
return;
}
this.locationMarkers = [];
this.geofenceMarkers = [];
this.geofenceHitMarkers = [];
let latLng = new google.maps.LatLng(-34.9290, 138.6010);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
mapTypeControl: false,
panControl: false,
rotateControl: false,
scaleControl: false,
streetViewControl: false,
disableDefaultUI: true
};
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
// Create LongPress event-handler
new LongPress(this.map, 500);
// Tap&hold detected. Play a sound a draw a circular cursor.
google.maps.event.addListener(this.map, 'longpresshold', this.onLongPressStart.bind(this));
// Longpress cancelled. Get rid of the circle cursor.
google.maps.event.addListener(this.map, 'longpresscancel', this.onLongPressCancel.bind(this));
// Longpress initiated, add the geofence
google.maps.event.addListener(this.map, 'longpress', this.onLongPress.bind(this));
// Blue current location marker
this.currentLocationMarker = new google.maps.Marker({
zIndex: 10,
map: this.map,
title: 'Current Location',
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 12,
fillColor: COLORS.blue,
fillOpacity: 1,
strokeColor: COLORS.white,
strokeOpacity: 1,
strokeWeight: 6
}
});
// Light blue location accuracy circle
this.locationAccuracyCircle = new google.maps.Circle({
map: this.map,
zIndex: 9,
fillColor: COLORS.light_blue,
fillOpacity: 0.4,
strokeOpacity: 0
});
// Stationary Geofence
this.stationaryRadiusCircle = new google.maps.Circle({
zIndex: 0,
fillColor: COLORS.red,
strokeColor: COLORS.red,
strokeWeight: 1,
fillOpacity: 0.3,
strokeOpacity: 0.7,
map: this.map
});
// Route polyline
let seq = {
repeat: '30px',
icon: {
path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
scale: 1,
fillOpacity: 0,
strokeColor: COLORS.white,
strokeWeight: 1,
strokeOpacity: 1
}
};
this.polyline = new google.maps.Polyline({
map: this.map,
zIndex: 1,
geodesic: true,
strokeColor: COLORS.polyline_color,
strokeOpacity: 0.7,
strokeWeight: 7,
icons: [seq]
});
// Popup geofence cursor for adding geofences via LongPress
this.geofenceCursor = new google.maps.Marker({
clickable: false,
zIndex: 100,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 100,
fillColor: COLORS.green,
fillOpacity: 0.2,
strokeColor: COLORS.green,
strokeWeight: 1,
strokeOpacity: 0.7
}
});
resolve();
});
}
////
// UI event handlers
//
onClickMainMenu() {
this.isMainMenuOpen = !this.isMainMenuOpen;
if (this.isMainMenuOpen) {
this.bgService.playSound('OPEN');
} else {
this.bgService.playSound('CLOSE');
}
}
async onClickSettings() {
this.bgService.playSound('OPEN');
const modal = await this.modalController.create({
component: SettingsPage,
cssClass: 'my-custom-class',
animated: true,
componentProps: {
'bgService': this.bgService,
'settingsService': this.settingsService
}
});
modal.onDidDismiss().then(async (result:any) => {
// Update our view-state -- BackgroundGeolocation state may have changed in Settings screen.
const state = await BackgroundGeolocation.getState();
this.state.enabled = state.enabled;
this.state.isMoving = state.isMoving;
this.state.geofenceProximityRadius = state.geofenceProximityRadius;
this.state.trackingMode = state.trackingMode;
});
await modal.present();
}
async onClickRequestPermission() {
let providerState = await BackgroundGeolocation.getProviderState();
const alert = await this.alertCtrl.create({
header: 'Request Permission',
message: `Current Authorization Status: ${providerState.status}`,
cssClass: 'alert-wide',
buttons: [{
text: 'When in Use',
handler: () => { this.requestPermission('WhenInUse') }
}, {
text: 'Always',
handler: () => { this.requestPermission('Always') }
}]
});
alert.present();
}
async requestPermission(request) {
await BackgroundGeolocation.setConfig({locationAuthorizationRequest: request});
let status = await BackgroundGeolocation.requestPermission();
console.log('[requestPermission] status:', status);
const alert = await this.alertCtrl.create({
header: 'Permission Result',
message: `Authorization Status: ${status}`,
cssClass: 'alert-wide',
buttons: [{
text: 'Ok',
handler: () => { }
}]
});
alert.present();
}
async onClickSync() {
this.bgService.playSound('BUTTON_CLICK');
const onComplete = (message, result) => {
this.settingsService.toast(message, result);
this.isSyncing = false;
};
const count = await BackgroundGeolocation.getCount();
if (!count) {
this.settingsService.toast('Database is empty.');
return;
}
const message = 'Sync ' + count + ' location' + ((count>1) ? 's' : '') + '?';
this.settingsService.confirm('Confirm Sync', message, () => {
this.isSyncing = true;
BackgroundGeolocation.sync().then(rs => {
this.bgService.playSound('MESSAGE_SENT');
onComplete(MESSAGE.sync_success, count);
}).catch(error => {
onComplete(MESSAGE.sync_failure, error);
});
});
}
async onClickDestroyLocations() {
this.bgService.playSound('BUTTON_CLICK');
let settingsService = this.settingsService;
const onComplete = (message, result) => {
settingsService.toast(message, result);
this.isDestroyingLocations = false;
};
let count = await BackgroundGeolocation.getCount();
if (!count) {
this.settingsService.toast('Locations database is empty');
return;
}
// Confirm destroy
let message = 'Destroy ' + count + ' location' + ((count>1) ? 's' : '') + '?';
this.settingsService.confirm('Confirm Delete', message, () => {
// Good to go...
this.isDestroyingLocations = true;
BackgroundGeolocation.destroyLocations().then(result => {
this.bgService.playSound('MESSAGE_SENT');
onComplete.call(this, MESSAGE.destroy_locations_success, count);
}).catch(error => {
onComplete.call(this, MESSAGE.destroy_locations_failure, error);
});
});
}
async onClickEmailLogs() {
this.bgService.playSound('BUTTON_CLICK');
const storage = (<any>window).localStorage;
const email = storage.getItem('settings:email');
if (!email) {
// Prompt user to enter a unique identifier for tracker.transistorsoft.com
const prompt = await this.alertCtrl.create({
backdropDismiss: false,
header: 'Email Logs',
message: 'Please enter your email address',
inputs: [{
name: 'email',
placeholder: 'Email address'
}],
buttons: [{
text: 'Cancel',
handler: (data: any) => {
prompt.dismiss();
}
}, {
text: 'OK',
handler: (data: any) => {
if (data.email.length < 1) {
return;
}
storage.setItem('settings:email', data.email);
this.doEmailLog(data.email);
}
}]
});
prompt.present();
} else {
this.doEmailLog(email);
}
}
async doEmailLog(email) {
const spinner = await this.loadingCtrl.create({
cssClass: 'my-custom-class',
message: 'Preparing logs...'
});
spinner.present();
this.isEmailingLog = true;
BackgroundGeolocation.logger.emailLog(email).then(result => {
spinner.dismiss();
this.isEmailingLog = false;
}).catch(error => {
spinner.dismiss();
this.isEmailingLog = false;
console.warn('- email log failed: ', error);
});
}
onClickResetOdometer() {
this.state.odometer = '0.0';
this.bgService.playSound('BUTTON_CLICK');
this.isResettingOdometer = true;
this.resetMarkers();
let settingsService = this.settingsService;
const onComplete = (message, result?) => {
settingsService.toast(message, result);
this.isResettingOdometer = false;
};
BackgroundGeolocation.resetOdometer().then((location) => {
onComplete.call(this, MESSAGE.reset_odometer_success);
}).catch((error) => {
onComplete.call(this, MESSAGE.reset_odometer_failure, error);
});
}
// Return to Home screen (app switcher)
onClickHome() {
this.router.navigate(['/home']);
}
async onToggleEnabled() {
const state = await BackgroundGeolocation.getState();
if (state.enabled === this.state.enabled) {
// The plugin is already in the desired state. Ignored. onToggleEnabled fires on initial boot.
return;
}
this.bgService.playSound('BUTTON_CLICK');
if (this.state.enabled) {
let onSuccess = (state) => {
console.log('[js] START SUCCESS :', state);
};
let onFailure = (error) => {
console.error('[js] START FAILURE: ', error);
};
if (this.state.trackingMode == 1) {
BackgroundGeolocation.start().then(onSuccess).catch(onFailure);
} else {
BackgroundGeolocation.startGeofences().then(onSuccess).catch(onFailure);
}
} else {
await BackgroundGeolocation.stop();
this.state.isMoving = false;
this.clearMarkers();
}
}
onClickWatchPosition() {
this.isWatchingPosition = !this.isWatchingPosition;
if (this.isWatchingPosition) {
BackgroundGeolocation.watchPosition((location) => {
console.log('*** [watchPosition]', location);
}, (error) => {
console.warn('*** [watchPosition] ERROR: ', error);
}, {
interval: 1000
});
} else {
BackgroundGeolocation.stopWatchPosition();
}
}
onClickGetCurrentPosition() {
this.bgService.playSound('BUTTON_CLICK');
BackgroundGeolocation.getCurrentPosition({
maximumAge: 0,
desiredAccuracy: 100,
samples: 1,
persist: true,
timeout: 30,
extras: {
foo: 'bar'
}
}).then(location => {
console.log('[js] getCurrentPosition: ', location);
}).catch(error => {
console.warn('[js] getCurrentPosition FAILURE: ', error);
});
}
/**
* My private test mode. DO NOT USE
* @private
*/
onClickTestMode() {
this.bgService.playSound('TEST_MODE_CLICK');
this.testModeClicks++;
if (this.testModeClicks == 10) {
this.bgService.playSound('TEST_MODE_SUCCESS');
this.settingsService.applyTestConfig();
}
if (this.testModeTimer > 0) clearTimeout(this.testModeTimer);
this.testModeTimer = setTimeout(() => {
this.testModeClicks = 0;
}, 2000);
}
onClickChangePace() {
if (!this.state.enabled) {
return;
}
const onComplete = () => {
this.state.isChangingPace = false;
}
this.bgService.playSound('BUTTON_CLICK');
this.state.isChangingPace = true;
this.state.isMoving = !this.state.isMoving;
BackgroundGeolocation.changePace(this.state.isMoving).then(onComplete).catch(onComplete);
}
////
// Background Geolocation event-listeners
//
/**
* @event location
*/
onLocation(location:Location) {
console.log('[location] -', JSON.stringify(location, null, 2));
// Print a log message to SDK's logger to prove this executed, even in the background.
BackgroundGeolocation.logger.debug("👍 [onLocation] received location in Javascript: " + location.uuid);
this.zone.run(() => {
this.setCenter(location);
if (!location.sample) {
// Convert meters -> km -> round nearest hundredth -> fix float xxx.x
this.state.odometer = parseFloat((Math.round((location.odometer/1000)*10)/10).toString()).toFixed(1);
}
});
}
/**
* @event location failure
*/
onLocationError(error:number) {
console.warn('[location] - ERROR: ', error);
}
/**
* @event motionchange
*/
onMotionChange(event:MotionChangeEvent) {
console.log('[motionchange] -', event.isMoving, event.location);
this.zone.run(() => {
if (event.isMoving) {
this.hideStationaryCircle();
} else {
this.showStationaryCircle(event.location);
}
this.state.enabled = true;
this.state.isChangingPace = false;
this.state.isMoving = event.isMoving;
});
}
/**
* @event heartbeat
*/
onHeartbeat(event:HeartbeatEvent) {
console.log('[heartbeat] -', event);
}
/**
* @event activitychange
*/
onActivityChange(event:MotionActivityEvent) {
console.log('[activitychange] -', event.activity, event.confidence);
this.zone.run(() => {
this.state.activityName = event.activity;
this.state.activityIcon = this.iconMap['activity_' + event.activity];
});
}
/**
* @event providerchange
*/
onProviderChange(provider:ProviderChangeEvent) {
console.log('[providerchange] -', provider);
switch(provider.status) {
case BackgroundGeolocation.AUTHORIZATION_STATUS_DENIED:
break;
case BackgroundGeolocation.AUTHORIZATION_STATUS_ALWAYS:
break;
case BackgroundGeolocation.AUTHORIZATION_STATUS_WHEN_IN_USE:
break;
}
this.zone.run(() => {
this.state.provider = provider;
});
}
/**
* @event geofenceschange
*/
onGeofencesChange(event:GeofencesChangeEvent) {
console.log('[geofenceschange] -', event);
// All geofences off
if (!event.on.length && !event.off.length) {
this.geofenceMarkers.forEach((circle) => {
circle.setMap(null);
});
this.geofenceMarkers = [];
return;
}
// Filter out all "off" geofences.
this.geofenceMarkers = this.geofenceMarkers.filter((circle) => {
if (event.off.indexOf(circle.identifier) < 0) {
return true;
} else {
circle.setMap(null);
return false;
}
});
// Add new "on" geofences.
event.on.forEach((geofence:Geofence) => {
var circle = this.geofenceMarkers.find((marker) => { return marker.identifier === geofence.identifier;});
// Already added?
if (circle) { return; }
this.geofenceMarkers.push(this.buildGeofenceMarker(geofence));
});
}
/**
* @event geofence
*/
async onGeofence(event:GeofenceEvent) {
console.log('[geofence] -', event);
var circle = this.geofenceMarkers.find((marker) => {
return marker.identifier === event.identifier;
});
if (!circle) { return; }
var map = this.map;
let location = event.location;
let geofenceMarker = this.geofenceHits[event.identifier];
if (!geofenceMarker) {
geofenceMarker = {
circle: new google.maps.Circle({
zIndex: 100,
fillOpacity: 0,
strokeColor: COLORS.black,
strokeWeight: 1,
strokeOpacity: 1,
radius: circle.getRadius()+1,
center: circle.getCenter(),
map: map
}),
events: []
};
this.geofenceHits[event.identifier] = geofenceMarker;
this.geofenceHitMarkers.push(geofenceMarker.circle);
}
var color;
if (event.action === 'ENTER') {
color = COLORS.green;
} else if (event.action === 'DWELL') {
color = COLORS.gold;
} else {
color = COLORS.red;
}
let circleLatLng = geofenceMarker.circle.getCenter();
let locationLatLng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
let distance = google.maps.geometry.spherical.computeDistanceBetween (circleLatLng, locationLatLng);
// Push event
geofenceMarker.events.push({
action: event.action,
location: event.location,
distance: distance
});
let heading = google.maps.geometry.spherical.computeHeading(circleLatLng, locationLatLng);
let circleEdgeLatLng = google.maps.geometry.spherical.computeOffset(circleLatLng, geofenceMarker.circle.getRadius(), heading);
geofenceMarker.events.push({
location: event.location,
action: event.action,
distance: distance
});
var geofenceEdgeMarker = new google.maps.Marker({
zIndex: 1000,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: color,
fillOpacity: 0.7,
strokeColor: COLORS.black,
strokeWeight: 1,
strokeOpacity: 1
},
map: map,
position: circleEdgeLatLng
});
this.geofenceHitMarkers.push(geofenceEdgeMarker);
var locationMarker = this.buildLocationMarker(location, {
showHeading: true
});
locationMarker.setMap(map);
this.geofenceHitMarkers.push(locationMarker);
var polyline = new google.maps.Polyline({
map: map,
zIndex: 1000,
geodesic: true,
strokeColor: COLORS.black,
strokeOpacity: 1,
strokeWeight: 1,
path: [circleEdgeLatLng, locationMarker.getPosition()]
});
this.geofenceHitMarkers.push(polyline);
// Change the color of activated geofence to light-grey.
circle.activated = true;
circle.setOptions({
fillColor: COLORS.grey,
fillOpacity: 0.2,
strokeColor: COLORS.grey,
strokeOpacity: 0.4
});
}
/**
* @event http
*/
onHttp(response:HttpEvent) {
if (response.success) {
console.log('[http] - success: ', response);
} else {
console.warn('[http] - FAILURE: ', response);
}
}
/**
* @event schedule
*/
onSchedule(state:State) {
console.log('[schedule] - ', state);
this.zone.run(() => {
this.state.enabled = state.enabled;
});
}
/**
* @event powersavechange
*/
onPowerSaveChange(isPowerSaveMode) {
console.log('[js powersavechange: ', isPowerSaveMode);
this.settingsService.toast('Power-save mode: ' + ((isPowerSaveMode) ? 'ON' : 'OFF'), null, 5000);
this.zone.run(() => {
this.state.containerBorder = (isPowerSaveMode) ? CONTAINER_BORDER_POWER_SAVE_ON : CONTAINER_BORDER_POWER_SAVE_OFF;
});
}
/**
* @event connectivitychange
*/
onConnectivityChange(event:ConnectivityChangeEvent) {
this.settingsService.toast('connectivitychange: ' + event.connected);
console.log('[connectivitychange] -', event);
}
/**
* @event enabledchange
*/
onEnabledChange(enabled:boolean) {
this.settingsService.toast('enabledchange: ' + enabled);
console.log('[enabledchange] -', enabled);
this.zone.run(() => {
this.state.enabled = enabled;
this.state.isMoving = false;
});
}
/**
* @event notificationaction
*/
onNotificationAction(buttonId:string) {
console.log('[notificationaction] -', buttonId);
switch(buttonId) {
case 'notificationButtonFoo':
break;
case 'notificaitonButtonBar':
break;
}
}
////
// Google map methods
//
//
//
private setCenter(location:Location) {
this.updateCurrentLocationMarker(location);
setTimeout(function() {
this.map.setCenter(new google.maps.LatLng(location.coords.latitude, location.coords.longitude));
}.bind(this));
}
private updateCurrentLocationMarker(location:Location) {
var latlng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
this.currentLocationMarker.setPosition(latlng);