Skip to content

Instantly share code, notes, and snippets.

@christocracy
Last active September 6, 2018 15:31
Show Gist options
  • Save christocracy/2abf5587cc12b83e15aa12958de7a7d2 to your computer and use it in GitHub Desktop.
Save christocracy/2abf5587cc12b83e15aa12958de7a7d2 to your computer and use it in GitHub Desktop.
Simple Cordova Background Geolocation Implementation for Ionic 2 / 3
/**
* How to implement cordova-background-geolocation with Ionic 2 / 3
* https://github.com/transistorsoft/cordova-background-geolocation-lt
* Chris Scott, Transistor Software <[email protected]>
*/
import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
/**
* Reference to BackgroundGeolocation
*/
private bgGeo: any;
constructor(public navCtrl: NavController, public platform: Platform) {
platform.ready().then(this.configureBackgroundGeolocation.bind(this));
}
configureBackgroundGeolocation() {
// 1. Get a reference to the plugin
this.bgGeo = (<any>window).BackgroundGeolocation;
// 2. Listen to events
this.bgGeo.on('location', this.onLocation.bind(this));
this.bgGeo.on('motionchange', this.onMotionChange.bind(this));
this.bgGeo.on('activitychange', this.onActivityChange.bind(this));
this.bgGeo.on('geofence', this.onGeofence.bind(this));
this.bgGeo.on('http', this.onHttpSuccess.bind(this), this.onHttpFailure.bind(this));
// 3. Configure it.
this.bgGeo.configure({
debug: true,
desiredAccuracy: 0,
distanceFilter: 10,
url: 'http://192.168.11.100:8080/locations',
autoSync: true
}, (state) => {
// 4. Start the plugin.
this.bgGeo.start();
});
}
onLocation(location, taskId) {
console.log('- location: ', location);
this.bgGeo.finish(taskId);
}
onMotionChange(isMoving, location, taskId) {
console.log('- motionchange: ', isMoving, location);
this.bgGeo.finish(taskId);
}
onActivityChange(activity) {
console.log('- activitychange: ', activity);
}
onGeofence(params, taskId) {
console.log('- geofence: ', params);
this.bgGeo.finish(taskId);
}
onHttpSuccess(response) {
console.log('- http success: ', response);
}
onHttpFailure(response) {
console.log('- http failure: ', response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment