Ionic 5 Get Background Geolocation of Device Example Application

In this Ionic 5/4 tutorial, we’ll learn How to fetch Geolocation in Ionic application when the application is moved to the background or minimized using Cordova and Native 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…

By.

•

min read

In this Ionic 5/4 tutorial, we’ll learn How to fetch Geolocation in Ionic application when the application is moved to the background or minimized using Cordova and Native 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 application to track Background Geolocation using the Cordova plugin and Ionic Native wrapper.

So, let’s begin …

Before we start with the application make sure that your system is having an 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 🙂

12 responses to “Ionic 5 Get Background Geolocation of Device Example Application”

  1. sayali dhomase Avatar

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

  2. kapil soni Avatar
    kapil soni

    •

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

    1. Nashit Nakade Avatar
      Nashit Nakade

      •

      to enable background add background plugin

  3. kapil soni Avatar
    kapil soni

    •

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

    1. Nashit Nakade Avatar
      Nashit Nakade

      •

      plugin not installed error will come if ionic serve connect your phone and run ionic cordova run android –livereload –device

      make sure your device is showing in my computer

  4. Adit Bharadwaj Avatar
    Adit Bharadwaj

    •

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

  5. chetan Avatar
    chetan

    •

    i am getting error while using given code

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Chetan, please explain the error you are facing.

      1. Raul Flores Avatar
        Raul Flores

        •

        plugin_not_installed

        1. Jolly.exe Avatar
          Jolly.exe

          •

          hmmmmm… Sometimes such issues appear from another universe… try to remove and add Cordova and Ionic native plugin again … let me know if it helped

        2. Nashit Nakade Avatar
          Nashit Nakade

          •

          this error comes when ur debugging it on device thru ionic cordova run. it will not come once u deploy apk

Leave a Reply

Your email address will not be published. Required fields are marked *