-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-map.ts
617 lines (557 loc) · 16.5 KB
/
simple-map.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
import {
Component,
ViewChild,
ElementRef,
NgZone
} from '@angular/core';
import {
IonicPage,
NavController,
NavParams,
ToastController,
AlertController,
LoadingController,
Platform
} from 'ionic-angular';
////
// NOTE: normally you will simply import from "cordova-background-geolocation-lt" or "cordova-background-geolocation"
// from "../../cordova-background-geolocation" is only fro convenience in the SampleApp for easily switching
// between public / private version of the plugin
//
import BackgroundGeolocation, {
Location,
HttpEvent,
HeartbeatEvent,
MotionActivityEvent,
ProviderChangeEvent,
MotionChangeEvent,
ConnectivityChangeEvent,
DeviceInfo,
TransistorAuthorizationToken
} from "../../cordova-background-geolocation";
import ENV from "../../ENV";
// Cordova plugins Device & Dialogs
import { Dialogs } from '@ionic-native/dialogs/ngx';
// Handy color & sound constants.
import COLORS from '../../lib/colors';
import SOUND_MAP from '../../lib/sound-map';
// Google maps <script> is loaded in main index.html
declare var google;
@IonicPage()
@Component({
selector: 'page-simple-map',
templateUrl: 'simple-map.html',
})
export class SimpleMapPage {
@ViewChild('map') mapElement: ElementRef;
// Background Geolocation State
deviceInfo: DeviceInfo;
state: any;
enabled: boolean;
isMoving: boolean;
distanceFilter: number;
stopTimeout: number;
autoSync: boolean;
stopOnTerminate: boolean;
startOnBoot: boolean;
debug: boolean;
provider: any;
// UI State
menuActive: boolean;
motionActivity: string;
odometer: string;
// Google Map references
map: any;
locationMarkers: any;
currentLocationMarker: any;
lastLocation: any;
stationaryRadiusCircle: any;
polyline: any;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private toastCtrl: ToastController,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController,
private zone:NgZone,
private platform:Platform,
private dialogs: Dialogs
) {
this.platform.ready().then(this.onDeviceReady.bind(this));
this.state = {};
// BackgroundGeolocation initial config.
this.isMoving = false;
this.enabled = false;
this.autoSync = true;
this.distanceFilter = 10;
this.stopTimeout = 1;
this.stopOnTerminate = false;
this.startOnBoot = true;
this.debug = true;
// UI members.
this.motionActivity = 'Activity';
this.menuActive = false;
}
ionViewDidLoad() {
console.log('ionViewDidLoad HomePage');
this.configureMap();
}
onDeviceReady() {
BackgroundGeolocation.getDeviceInfo().then((deviceInfo) => {
this.deviceInfo = deviceInfo;
});
// We prompt you for a unique identifier in order to post locations tracker.transistorsoft.com
this.configureBackgroundGeolocation();
}
async configureBackgroundGeolocation() {
// Compose #url from username
let localStorage = (<any>window).localStorage;
// Fetch Transistor JSON Web Token from localStorage. For authorization with tracker.transistorsoft.com.
let token:TransistorAuthorizationToken = await BackgroundGeolocation.findOrCreateTransistorAuthorizationToken(
localStorage.getItem('orgname'),
localStorage.getItem('username'),
ENV.TRACKER_HOST);
////
// Step 1: listen to events
//
BackgroundGeolocation.onLocation(this.onLocation.bind(this));
BackgroundGeolocation.onMotionChange(this.onMotionChange.bind(this));
BackgroundGeolocation.onActivityChange(this.onActivityChange.bind(this));
BackgroundGeolocation.onHttp(this.onHttpSuccess.bind(this));
BackgroundGeolocation.onProviderChange(this.onProviderChange.bind(this));
BackgroundGeolocation.onHeartbeat(this.onHeartbeat.bind(this));
BackgroundGeolocation.onPowerSaveChange(this.onPowerSaveChange.bind(this));
BackgroundGeolocation.onConnectivityChange(this.onConnectivityChange.bind(this));
////
// Step 2: Initialize the plugin
//
BackgroundGeolocation.ready({
// Logging / Debug config
debug: this.debug,
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
// Geolocation config
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, // <-- highest possible accuracy
distanceFilter: this.distanceFilter,
// ActivityRecognition config
stopTimeout: this.stopTimeout,
// Application config
stopOnTerminate: this.stopOnTerminate,
startOnBoot: this.startOnBoot,
heartbeatInterval: 60,
// HTTP / Persistence config
url: ENV.TRACKER_HOST + '/api/locations',
authorization: {
strategy: 'JWT',
accessToken: token.accessToken,
refreshToken: token.refreshToken,
refreshUrl: ENV.TRACKER_HOST + '/api/refresh_token',
refreshPayload: {
refresh_token: '{refreshToken}'
},
expires: token.expires
},
autoSync: this.autoSync,
autoSyncThreshold: 0
}, (state) => {
console.log('- BackgroundGeolocation ready: ', state);
// Set current plugin state upon our view.
this.zone.run(() => {
this.enabled = state.enabled;
this.isMoving = state.isMoving;
this.autoSync = state.autoSync;
this.distanceFilter = state.distanceFilter;
this.stopTimeout = state.stopTimeout;
this.stopOnTerminate = state.stopOnTerminate;
this.startOnBoot = state.startOnBoot;
this.debug = state.debug;
});
});
}
/**
* @event location
*/
onLocation(location:Location) {
console.log('[event] location ', location);
this.zone.run(() => {
this.odometer = (location.odometer/1000).toFixed(1) + 'km';
});
this.updateCurrentLocationMarker(location);
}
/**
* @event motionchange
*/
onMotionChange(event:MotionChangeEvent) {
console.log('[event] motionchange, isMoving: ', event.isMoving, event.location);
this.zone.run(() => {
this.isMoving = event.isMoving;
});
// Show / hide the big, red stationary radius circle
if (!event.isMoving) {
let coords = event.location.coords;
let radius = 200;
let center = new google.maps.LatLng(coords.latitude, coords.longitude);
this.stationaryRadiusCircle.setRadius(radius);
this.stationaryRadiusCircle.setCenter(center);
this.stationaryRadiusCircle.setMap(this.map);
this.map.setCenter(center);
} else if (this.stationaryRadiusCircle) {
this.stationaryRadiusCircle.setMap(null);
}
}
/**
* @event activitychange
*/
onActivityChange(event:MotionActivityEvent) {
console.log('[event] activitychange: ', event);
this.zone.run(() => {
this.motionActivity = `${event.activity}:${event.confidence}%`;
});
}
/**
* @event http
*/
onHttpSuccess(response:HttpEvent) {
console.log('[event] http: ', response);
}
onHttpFailure(response:HttpEvent) {
console.warn('[event] http failure: ', response);
}
/**
* @event heartbeat
*/
onHeartbeat(event:HeartbeatEvent) {
let location = event.location;
// NOTE: this is merely the last *known* location. It is not the *current* location. If you want the current location,
// fetch it yourself with #getCurrentPosition here.
console.log('- heartbeat: ', location);
}
/**
* @event powersavechange
*/
onPowerSaveChange(isPowerSaveEnabled) {
this.dialogs.alert('[event] powersavechnage, Power-save mode enabled? ' + isPowerSaveEnabled);
console.log('[event] powersavechange, isPowerSaveEnabled: ', isPowerSaveEnabled);
}
onConnectivityChange(event:ConnectivityChangeEvent) {
console.log('[event] connectivitychange, connected? ', event.connected);
this.toast('[event] connectivitychange: Network connected? ', event.connected);
}
/**
* @event providerchange
*/
onProviderChange(provider:ProviderChangeEvent) {
this.provider = provider;
console.log('[event] providerchange: ', provider);
}
onClickMainMenu(item) {
this.menuActive = !this.menuActive;
this.playSound((this.menuActive) ? 'OPEN' : 'CLOSE');
}
onClickSync() {
this.hasRecords().then((count) => {
this.confirm(`Sync ${count} records to server?`).then(this.doSync.bind(this));
});
}
private doSync() {
BackgroundGeolocation.sync((records) => {
this.toast(`Synced ${records.length} records to server.`);
console.log('- #sync success: ', records.length);
}, (error) => {
console.warn('- #sync failure: ', error);
});
}
onClickDestroy() {
this.hasRecords().then((count) => {
this.confirm(`Destroy ${count} records?`).then(this.doDestroyLocations.bind(this));
}).catch(() => {
this.toast('Database is empty');
});
}
private doDestroyLocations() {
BackgroundGeolocation.destroyLocations(() => {
this.toast('Destroyed all records');
console.log('- #destroyLocations success');
}, (error) => {
console.warn('- #destroyLocations error: ', error);
});
}
private hasRecords() {
return new Promise((resolve, reject) => {
BackgroundGeolocation.getCount((count) => {
if (count > 0) {
resolve(count);
} else {
this.toast('Database is empty');
}
});
});
}
onClickEmailLog() {
this.getEmail().then((email) => {
this.confirm(`Email logs to ${email}?`).then(() => {
this.doEmailLog(email);
}).catch(() => {
// Clear email from localStorage and redo this action.
let localStorage = (<any>window).localStorage;
localStorage.removeItem('email');
this.onClickEmailLog();
});
});
}
private doEmailLog(email) {
// Show spinner
let loader = this.loadingCtrl.create({content: "Creating log file..."});
loader.present();
BackgroundGeolocation.emailLog(email, () => {
loader.dismiss();
}, (error) => {
loader.dismiss();
console.warn('#emailLog error: ', error);
});
}
onClickDestroyLog() {
this.confirm("Destroy logs?").then(this.doDestroyLog.bind(this));
}
private doDestroyLog() {
let loader = this.loadingCtrl.create({content: "Destroying logs..."});
loader.present();
BackgroundGeolocation.destroyLog(() => {
loader.dismiss();
this.toast('Destroyed logs');
}, (error) => {
loader.dismiss();
this.toast('Destroy logs failed: ' + error);
});
}
onSetConfig(name) {
if (this.state[name] === this[name]) {
// No change. do nothing.
return;
}
// Careful to convert string -> number from <ion-input> fields.
switch(name) {
case 'distanceFilter':
case 'stopTimeout':
this[name] = parseInt(this[name], 10);
break;
}
// Update state
this.state[name] = this[name];
let config = {};
config[name] = this[name];
// #setConfig
BackgroundGeolocation.setConfig(config, (state) => {
this.toast(`#setConfig ${name}: ${this[name]}`);
});
}
/**
* [Home] button clicked. Goo back to home page
*/
onClickHome() {
this.navCtrl.setRoot('HomePage');
}
/**
* #start / #stop tracking
*/
onToggleEnabled() {
console.log('- enabled: ', this.enabled);
if (this.enabled) {
BackgroundGeolocation.start((state) => {
console.log('- Start success: ', state);
});
} else {
this.isMoving = false;
this.stationaryRadiusCircle.setMap(null);
BackgroundGeolocation.stop((state) => {
console.log('- Stop success: ', state);
});
}
}
/**
* Toggle moving / stationary state
*/
onClickChangePace() {
if (!this.enabled) {
this.toast('You cannot changePace while plugin is stopped');
return;
}
this.isMoving = !this.isMoving;
BackgroundGeolocation.changePace(this.isMoving, () => {
console.log('- changePace success');
});
}
/**
* Get the current position
*/
onClickGetCurrentPosition() {
BackgroundGeolocation.getCurrentPosition({}, (location) => {
console.log('- getCurrentPosition success: ', location);
});
}
/**
* Configure the google map
*/
private configureMap() {
/**
* Configure Google Maps
*/
this.locationMarkers = [];
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);
// 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
}
});
// Red 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
this.polyline = new google.maps.Polyline({
map: this.map,
zIndex: 1,
geodesic: true,
strokeColor: COLORS.polyline_color,
strokeOpacity: 0.7,
strokeWeight: 7,
icons: [{
repeat: '30px',
icon: {
path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
scale: 1,
fillOpacity: 0,
strokeColor: COLORS.white,
strokeWeight: 1,
strokeOpacity: 1
}
}]
});
}
/**
* Update the lat/lng of blue current location marker
*/
private updateCurrentLocationMarker(location) {
var latlng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
this.currentLocationMarker.setPosition(latlng);
setTimeout(() => {
this.map.setCenter(new google.maps.LatLng(location.coords.latitude, location.coords.longitude));
});
if (location.sample === true) {
return;
}
if (this.lastLocation) {
this.locationMarkers.push(this.buildLocationMarker(location));
}
// Add breadcrumb to current Polyline path.
this.polyline.getPath().push(latlng);
this.lastLocation = location;
}
/**
* Build a new Google Map location marker with direction icon
*/
private buildLocationMarker(location, options?) {
options = options || {};
return new google.maps.Marker({
zIndex: 1,
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
rotation: location.coords.heading,
scale: 2,
anchor: new google.maps.Point(0, 2.6),
fillColor: COLORS.polyline_color,
fillOpacity: 1,
strokeColor: COLORS.black,
strokeWeight: 1,
strokeOpacity: 1
},
map: this.map,
position: new google.maps.LatLng(location.coords.latitude, location.coords.longitude)
});
}
/**
* Fetch email address from localStorage. We use this for #emailLog method
* @return Promise
*/
private getEmail() {
let localStorage = (<any>window).localStorage;
let email = localStorage.getItem('email');
return new Promise((resolve, reject) => {
if (email) { return resolve(email); }
this.dialogs.prompt('Email address', 'Email Logs').then((response) => {
if (response.buttonIndex === 1 && response.input1.length > 0) {
let email = response.input1;
localStorage.setItem('email', email);
resolve(email);
}
});
});
}
/**
* Send a Toast message
*/
private toast(message, duration?) {
this.toastCtrl.create({
message: message,
cssClass: 'toast',
duration: duration || 3000
}).present();
}
/**
* Confirm stuff
*/
private confirm(message) {
return new Promise((resolve, reject) => {
let alert = this.alertCtrl.create({
title: 'Confirm',
message: message,
buttons: [{
text: 'Cancel',
role: 'cancel'
}, {
text: 'Confirm',
handler: resolve
}]
});
alert.present();
});
}
/**
* Play a UI sound via BackgroundGeolocation#playSound
*/
private playSound(name) {
let soundId = SOUND_MAP[this.deviceInfo.platform.toUpperCase()][name.toUpperCase()];
if (!soundId) {
console.warn('playSound: Unknown sound: ', name);
}
BackgroundGeolocation.playSound(soundId);
}
}