Ionic 3, Angular 5 and Cordova Geofence with Google Places API

by Didin J. on Jul 07, 2018 Ionic 3, Angular 5 and Cordova Geofence with Google Places API

A comprehensive tutorial on how to build Ionic 3, Angular 5 and Cordova Geofence App using Native Cordova Geofence Plugin and Google Places API

A comprehensive tutorial on how to build Ionic 3, Angular 5 and Cordova Geofence App using Native Cordova Geofence Plugin and Google Places API. We will put multiple Geofence latitude/longitude to the app that gets from Google Places API. For the Google Places API, we will use Google Places. Previously we have shown you how to use Google Places API and Google Maps.

Table of Contents:

A Geofence is a virtual perimeter for a real-world geographic area. A Geofence could be dynamically generated as in a radius around a point location, or a Geofence can be a predefined set of boundaries such as school zones, neighborhood, store, food, or public facility boundaries.

The following tools, framework, and modules are required for this tutorial:

  1. Ionic 3
  2. Node.js
  3. Angular 5
  4. Cordova
  5. Google Places API
  6. Terminal or Node.js Command Line
  7. IDE or Text Editor

Before moving to the steps, make sure you have installed the latest Node.js and Ionic 3. To check it, type this command in the terminal or Node.js command line.

node -v
v8.11.1
npm -v
6.1.0
ionic -v
3.20.0
cordova -v
8.0.0

That's the last version when this tutorial was written. For update Node.js and it's `npm` download from Node.js and choose the recommended version. For Ionic 3, type this command.

sudo npm i -D -E ionic@latest
sudo npm i -g [email protected]

Above command is downgrade Cordova version to earlier version, because of it still a lot of trouble when using Cordova 8.0.0.


Setup Google Places API

Open your browser then go to `https://console.developers.google.com` address. Login using your Google account and you will be redirected to API dashboard.

Ionic 3, Angular 5 and Cordova Geofence with Google Places API - Google APIs Dashboard

If you don't have a project yet, click the drop-down menu on the right side of the Google APIs logo.

Ionic 3, Angular 5 and Cordova Geofence with Google Places API - Select App

Click the plus button to create a new project.

Ionic 3, Angular 5 and Cordova Geofence with Google Places API - App Name

Fill out the project name and click `Create` button. As you see, our Google APIs has reached maximum project, so we will use our existing project for this tutorial. After creating a new project, it will back to the project dashboard. Click the `Enable APIs and Services` button then click `View All` in the Maps category.

Ionic 3, Angular 5 and Cordova Geofence with Google Places API - Choose API

Find and click the `Google Places API Web Service`.

Ionic 3, Angular 5 and Cordova Geofence with Google Places API - Enable API

Click the `ENABLE` button to enable the Google Places API Web Service. Back to the project dashboard then do the same way to enable Google Maps Javascript API. Now, click the `Credentials` menu on the left menu then click `Create Credentials` drop-down button.

Ionic 3, Angular 5 and Cordova Geofence with Google Places API - Create Credentials

Choose `API Key` then it will create an API Key. Write down and save to your notepad or text editor for use later.


Create a New Ionic 3, Angular 5 and Cordova App

To create a new Ionic 3, Angular 5 and Cordova app, type this command.

ionic start ionic-geofence blank

You will see this output, then type `Y` for including Cordova to the app creation.

✔ Creating directory ./ionic-geofence - done!
✔ Downloading and extracting blank starter - done!

? Would you like to integrate your new app with Cordova to target native iOS and Android? (y/N) y

Just wait for a few minutes because it will also install NPM modules. Next, go to the newly created app folder.

cd ./ionic-geofence

For sanitizing, run the app on the browser for the first time to make sure everything working properly.

ionic serve -l

And you will see this landing page of Ionic 3 and Angular 5 app.

Ionic 3, Angular 5 and Cordova Geofence with Google Places API - Ionic Blank


Configure Google Places Javascript APIs for The Ionic 3 app

To integrated Google Places Javascript APIs for The Ionic 3 app, open and edit `src/index.html` then add this script reference before the closing of the body tag.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

Replace `YOUR_API_KEY` with the Google API Key that you write to the Notepad in the previous step. Next, open and edit `src/pages/home/home.html` then replace `<ion-content>` tags with this.

<ion-content>
  <div #map id="map"></div>
</ion-content>

We use Google maps as a requirement for Google Places Search API. Next, open and edit `src/pages/home/home.ts` then modify these imports.

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';

Declare required variables before the `@Component`.

declare var google;
let map: any;

Declare this variable before the constructor.

@ViewChild('map') mapElement: ElementRef;

Inject Platform module to the constructor params.

constructor(public navCtrl: NavController, public platform: Platform) {}

Create a function to get Google Places after the constructor.

getPlaces() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -6.854359, lng: 107.598455},
    zoom: 17
  });
  let service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: {lat: -6.854359, lng: 107.598455},
    radius: 500,
    type: ['restaurant']
  }, (results,status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        console.log(results[i]);
      }
    }
  });
}

Call that function inside `platform.ready` in the constructor body.

constructor(public navCtrl: NavController, public platform: Platform) {
  platform.ready().then(() => {
    this.getPlaces();
  });
}

Run the Ionic 3 app in the browser by typing this command.

ionic serve -l

Then you should see the places on the console of the browser.


Install and Configure Ionic Cordova Native Geofence Plugin

To install Ionic Cordova Native Geofence Plugin type this commands.

ionic cordova plugin add cordova-plugin-geofence
npm install --save @ionic-native/geofence

Next, open and edit `src/app/app.module.ts` then add this import.

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

Register `Geofence` module to `@NgModule` providers.

providers: [
  StatusBar,
  SplashScreen,
  Geofence,
  {provide: ErrorHandler, useClass: IonicErrorHandler}
]

Now, Geofence is ready to use in your Ionic 3 app.


Set Geofence from Loaded Google Places

To set Geofences using loaded coordinates from Google places, open and edit again `src/pages/home/home.ts` then add this import.

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

Inject Geofence module to the constructor params.

constructor(public navCtrl: NavController, public platform: Platform, private geofence: Geofence)

Initialize Geofence in the constructor body before the Google places loaded.

constructor(public navCtrl: NavController, public platform: Platform, private geofence: Geofence) {
  geofence.initialize().then(
    () => console.log('Geofence Plugin Ready'),
    (err) => console.log(err)
  )

  platform.ready().then(() => {
    this.getPlaces();
  });
}

Create a new function for add Geofence.

private addGeofence(id, idx, lat, lng, place, desc) {
  let fence = {
    id: id,
    latitude: lat,
    longitude: lng,
    radius: 50,
    transitionType: 3,
    notification: {
        id: idx,
        title: 'You crossed ' + place,
        text: desc,
        openAppOnClick: true
    }
  }

  this.geofence.addOrUpdate(fence).then(
     () => console.log('Geofence added'),
     (err) => console.log('Geofence failed to add')
   );
}

Call this function in the get places function results extraction. So, the function of getting places will look like this.

getPlaces() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -6.854359, lng: 107.598455},
    zoom: 17
  });
  let service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: {lat: -6.854359, lng: 107.598455},
    radius: 500,
    type: ['restaurant']
  }, (results, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        this.addGeofence(results[i].id, i+1, results[i].geometry.location.lat(), results[i].geometry.location.lng(), results[i].name, results[i].vicinity);
      }
    }
  });
}

Now, the Ionic 3, Angular 5 and Cordova Geofence App is ready to run in the real device.


Run the Ionic 3, Angular 5 and Cordova Geofence App

It's time to run the app in the real device. We start to run this app to an Android device (we use an old Android 4.4.2). First, remove and add Cordova Android platform.

ionic cordova platform rm android
ionic cordova platform add [email protected]

Connect your Android device then type this command to run the app.

ionic cordova run android

You will see the blank Ionic 3 app only, but there's a Geofence working after load the Google Places on the background. To make Geofence Plugin working, turn off then turn on the device but ours working without restarting the device. If you near the radius 50 from the coordinates of the place, the app will show the notification like this.

Ionic 3, Angular 5 and Cordova Geofence with Google Places API - Geofence Notification

For iOS, type this command to remove and add the Cordova iOS platform first.

ionic cordova platform rm ios
ionic cordova platform add [email protected]

Build the Cordova app using this command.

ionic cordova build ios

Open the `platforms/ios/ionic-geofence.xcworkspace` using XCode then run the app to the device using XCode.

That it's, the Ionic 3, Angular 5 and Cordova Geofence App. You can find the working source code in our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:

Thanks!