Ionic 4/5 Geofence Tutorial using Native Plugin

The geofence is an area defined in a geometrical shape which can be a circle or any polygon shape around a coordinate on a Geological map. In google maps, a Geofence is used to know if the current device has entered or exited from a geofence. Indication about leaving or exiting a Geofence can be…

By.

•

min read

The geofence is an area defined in a geometrical shape which can be a circle or any polygon shape around a coordinate on a Geological map. In google maps, a Geofence is used to know if the current device has entered or exited from a geofence.

Indication about leaving or exiting a Geofence can be shown in the form of notification a user which can have a number of practical applications in day to day life. For example, we can add a location to remind use when we enter that geofence for shopping some important items.

In this article, we will learn How to add Geofence functionality in a Hybrid application like Ionic use this feature. It can work background and keep watch if the current location is in a Geofence or not to give local notification to the user.

Let’s get started!

Install Geofence Native and Cordova Plugins

Run following commands in the Ionic project root to install Geofence Cordova plugin and Angular wrapper for it:

$ ionic cordova plugin add cordova-plugin-geofence
$ npm install @ionic-native/geofence</pre>
<h3>Add in App Module Imports</h3>
To use these plugin methods we need to import the <code>Geofence class then add in the providers array:
// app.module.ts
...

import { Geofence } from '@ionic-native/geofence/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    Geofence,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Using Geofence in the Component

To use Geofence we need to import the Geofence class and also add in class constructor as shown below:

// home.page.ts
import { Component } from '@angular/core';

import { Geofence } from '@ionic-native/geofence/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage  implements OnInit {


  constructor(
    private geofence: Geofence
  ) {
		  // initialize the plugin
			geofence.initialize().then(
				// resolved promise does not return a value
				() => alert('Geofence Plugin Ready'),
				(err) => alert(err)
			  )
			  
	  }
	  
...
...

In above code, we are also checking if Geofence is loaded successfully using geofence.initialize() on class load.

Next call the addOrUpdate method  which returns a promise and takes option object which is fence here.

// home.page.ts
import { Component } from '@angular/core';

import { Geofence } from '@ionic-native/geofence/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage  implements OnInit {


  constructor(
    private geofence: Geofence
  ) {
		  // initialize the plugin
			geofence.initialize().then(
				// resolved promise does not return a value
				() => alert('Geofence Plugin Ready'),
				(err) => alert(err)
			  )
		this.addGeofence()
	  }
	  

  addGeofence() {
    //options describing geofence
    let fence = {
      id: '69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb', //any unique ID
      latitude:       37.285951, //center of geofence radius
      longitude:      -121.936650,
      radius:         100, //radius to edge of geofence in meters
      transitionType: 3, //see 'Transition Types' below
      notification: { //notification settings
          id:             1, //any unique ID
          title:          'You crossed a fence', //notification title
          text:           'You just arrived to Gliwice city center.', //notification body
          openAppOnClick: true //open app when notification is tapped
      }
    }
  
    this.geofence.addOrUpdate(fence).then(
       () => console.log('Geofence added'),
       (err) => console.log('Geofence failed to add')
     );
  }
 }

 

 

One response to “Ionic 4/5 Geofence Tutorial using Native Plugin”

  1. Hunter Melnick Avatar
    Hunter Melnick

    •

    Im glad you decided to do this tutorial. Thanks man

Leave a Reply

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