Ionic 3 | Get Background Device Location using Cordova and Ionic Native Geolocation Plugins

Applications these days provide features to get locations like we implemented device location plugin to get location coordinates when a user clicks a button, But what if we want to get location updates after fixed intervals of time. To track location we can’t always keep an application open, In that case, we need to track location when the application is in the background.

In this tutorial, we will create an Ionic 3 application to track Background Geolocation using Cordova plugin and Ionic Native wrapper.

So, let’s begin …

Before we start with application make sure that your system is having updated version of NodeJS installed.

Create a new Ionic Application

Install latest version of Ionic and Cordova CLI.

$ npm install -g ionic cordova

Now we will create a new blank application

$ ionic start Ionic3BackgroundGeolocation blank

After the application is created, go to the root using the CD command

$ cd Ionic3BackgroundGeolocation

If your system is having Visual Studio code(VS Code) installed, use $ code .  command to open the project in VS Code

Install the Cordova and Ionic Native plugins

Background Geolocation

$ ionic cordova plugin add cordova-plugin-mauron85-background-geolocation
$ npm install --save @ionic-native/background-geolocation

This plugin will use device location service to fetch latitude, longitude, accuracy, altitude, altitudeAccuracy, altitudeAccuracy, heading, speed and start a background service to update location after an interval.

Local Notifications

$ ionic cordova plugin add cordova-plugin-local-notification
$ npm install --save @ionic-native/local-notifications

We are using Local Notification plugin to show location coordinates received from Background Geolocation plugin

Add these plugin in application's module file

In app.module.ts, import plugin and add in imports array.

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { BackgroundGeolocation } from '@ionic-native/background-geolocation';
import { LocalNotifications } from '@ionic-native/local-notifications';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    BackgroundGeolocation,
    LocalNotifications,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

In home.html, add following HTML

    <button ion-button (click)="startBackgroundGeolocation()">Start Background Geolocation</button>
    <button ion-button (click)="stopBackgroundGeolocation()">Stop Background Geolocation</button>

Here we have two buttons to start and stop background geolocation service.

Update component with methods

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { BackgroundGeolocation, BackgroundGeolocationConfig, BackgroundGeolocationResponse } from '@ionic-native/background-geolocation';
import { LocalNotifications } from '@ionic-native/local-notifications';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  config: BackgroundGeolocationConfig = {
    desiredAccuracy: 10,
    stationaryRadius: 20,
    distanceFilter: 30,
    debug: true, //  enable this hear sounds for background-geolocation life-cycle.
    stopOnTerminate: false, // enable this to clear background location settings when the app terminates
  };

  constructor(
    public navCtrl: NavController,
    private backgroundGeolocation: BackgroundGeolocation,
    private localNotifications: LocalNotifications
  ) {

    this.backgroundGeolocation.configure(this.config)
      .subscribe((location: BackgroundGeolocationResponse) => {

        console.log(location);
        this.showNotification(location)
        // IMPORTANT:  You must execute the finish method here to inform the native plugin that you're finished,
        // and the background-task may be completed.  You must do this regardless if your HTTP request is successful or not.
        // IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
        this.backgroundGeolocation.finish(); // FOR IOS ONLY

      });
  }

  startBackgroundGeolocation() {
    // start recording location
    this.backgroundGeolocation.start();
  }

  stopBackgroundGeolocation() {
    // If you wish to turn OFF background-tracking, call the #stop method.
    this.backgroundGeolocation.stop();
  }

  showNotification(data){
    // Schedule a single notification
    this.localNotifications.schedule({
      id: 1,
      text: JSON.stringify(data),
      sound: 'file://sound.mp3',
      data: { secret: "key" }
    });
  }

}

Above code is having Background Geolocation configuration object, and methods to start and stop Background location service. On successfully fetching location object we will show Local Notification having data of coordinates, accuracy, speed, time etc.

That's it you can now test your application in a real device after building apk using this command $ ionic cordova build android 

Let me know if you face any issue in implementing this

Happy coding 🙂

0 0 vote
Article Rating
Subscribe
Notify of
guest
12 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
sayali dhomase
1 month ago

i me this error in Property ‘subscribe’ does not exist on type ‘Promise

trackback
3 months ago

[…] having followed the instructions on this site, I got a long […]

kapil soni
kapil soni
9 months ago

not worked for me properly if am in backgound, please give me response if you create any post

kapil soni
kapil soni
1 year ago

hi team,
I have tried above but not working form me i got plugin not installed error?

Adit Bharadwaj
Adit Bharadwaj
1 year ago

i have solved my previous query i wanted to knw how can we print the coordinates and show them on notification or a div?

chetan
chetan
1 year ago

i am getting error while using given code