Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomysmile/1ca0086ebc1d42b41849429f662b0527 to your computer and use it in GitHub Desktop.
Save tomysmile/1ca0086ebc1d42b41849429f662b0527 to your computer and use it in GitHub Desktop.
Simple Cordova Background Geolocation Implementation for Ionic 2
/**
* How to implement cordova-background-geolocation with Ionic 2
* https://github.com/transistorsoft/cordova-background-geolocation-lt
* Chris Scott, Transistor Software <chris@transistorsoft.com>
*/
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