Ionic 5 Cordova Geolocation and Geocoder Tutorial with Examples

Last updated on by Digamber
This is a step by step tutorial on how to use Cordova Geolocation and Geocoder plugin in an Ionic 5 app to get the current user device position, get current user address.

In this tutorial we are going to learn how to get users device location with latitude and longitude.

We will learn to get the users address using Geolocation and Geocoder Plugins.

We will look at how to add target platforms such as iOS, Android or Windows and create the build in Ionic for various devices.

Prerequisite

We must have the latest version of Node js installed on our device. If you are not having then follow this tutorial on: How to Download and Install Node.js and npm

Create New Ionic / Angular Project

Use the command to install Ionic 5 Cordova globally on your machine.

sudo npm install -g cordova ionic

By using the following command, you can check the Ionic CLI version running on your machine.

ionic -v

# 5.4.13

Use below command to update Ionic and Cordova.

sudo npm update -g cordova ionic

Let’s start installing a brand new Ionic Angular app with the help of Ionic CLI, run the following command in your terminal.

ionic start ionic-geolocation-app blank --type=angular

Get inside the project folder.

cd ionic-geolocation-app

Start the app in the browser.

ionic serve --lab

How to Install & Configure Cordova Geolocation, Geocoder and Ionic Native Plugins

In this step, we will first install then configure Cordova Geolocation, Geocoder and Ionic native plugins in an Ionic 5 app.

Geolocation

The cordova-plugin-geolocation plugin API is based on the W3C Geolocation API Specification and helps to get the location (latitude and longitude) data.

This plugin provides information about the device’s location, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs.

ionic cordova plugin add cordova-plugin-geolocation

Install @ionic-native/geolocation via npm using the below command.

npm install @ionic-native/geolocation

This geo location plugin provides device data such as device location, latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs.

It supports following platforms:

  • iOS
  • Android
  • Windows
  • Browser
  • Amazon Fire OS

Add given below configuration to your configuration.xml file for iOS support.

<edit-config file="*-Info.plist" mode="merge" target="NSLocationWhenInUseUsageDescription">
   <string>We use your location for full functionality of certain app features.</string>
</edit-config>

Native Geocoder

The native geocoder plugin helps us to get the address for given coordinates and also does forward and reverse geocoding for iOS and Android platforms.

ionic cordova plugin add cordova-plugin-nativegeocoder

npm install @ionic-native/native-geocoder

Import Plugins in Main AppModule

Add the above plugins in the main Ionic app module file, open app.module.ts file, and import and add plugins in an import array.

// app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

// geolocation and native-geocoder
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NativeGeocoder } from '@ionic-native/native-geocoder/ngx';

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

export class AppModule {}

Get Current User’s Device Location Latitude and Longitude using Geolocation and Native Geocoder Plugin

Apps like Whatsapp, Uber, Ola, and many more depending on the user’s location, and without location, we can’t imagine modern days web and mobile applications. Almost every application uses the location service to offer excellent services to its users.

Finding a geo location with Cordova Geolocation is very easy, and We are going to get the current lat long of the user’s device.

In this step, I am going to describe how to locate the user’s device position, open home.pge.ts file and add the given code in it.

// home.page.ts

import { Component, NgZone } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';

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

export class HomePage {
  latitude: any = 0; //latitude
  longitude: any = 0; //longitude

  constructor(
    private geolocation: Geolocation
  ) {}

  options = {
    timeout: 10000, 
    enableHighAccuracy: true, 
    maximumAge: 3600
  };

  // use geolocation to get user's device coordinates
  getCurrentCoordinates() {
    this.geolocation.getCurrentPosition().then((resp) => {
      this.latitude = resp.coords.latitude;
      this.longitude = resp.coords.longitude;
     }).catch((error) => {
       console.log('Error getting location', error);
     });
  }
}

To get the geographical position of a user, we imported the Geolocation API at the top, then injected in the constructor and accessed the getCurrentPosition() method to get the user’s position.

The getCurrentPosition() method returns geolocation data which contains a timestamp, GeoLocation coordinates such as latitude, longitude, altitude, accuracy, alititudeAccuracy, heading and speed.

The getCurrentPosition() function takes 3 parameters, success, error and options. In the options we specify timeout, enableHighAccuracy and maximumAge.

Add the following code in home.page.html file.

// home.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>
        Ionic 4 Geolocation & Geocoder Examples
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">

    <ion-button (click)="getCurrentCoordinates()" expand="block">
      Get Location
    </ion-button>

  <ion-list>
    <ion-list-header>
      <ion-label>Location Coordinates</ion-label>
    </ion-list-header>
    <ion-item>
      <ion-label>
        Latitue
      </ion-label>
      <ion-badge color="danger" slot="end">{{latitude}}</ion-badge>
    </ion-item>
    <ion-item>
      <ion-label>
        Longitude
      </ion-label>
      <ion-badge color="danger" slot="end">{{longitude}}</ion-badge>
    </ion-item>
    </ion-list>    
  </div>
</ion-content>

Get Current User's Device Location Latitude and Longitude using Geolocation and Native Geocoder Plugin

Getting Current Address

To get the current address of the location. We need to import the following services at the header part of the Ionic TypeScript template.

import { NativeGeocoder, NativeGeocoderResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';

Open the home.page.ts file then add the following code.

import { Component, NgZone } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NativeGeocoder, NativeGeocoderResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';

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

export class HomePage {
  latitude: any = 0; //latitude
  longitude: any = 0; //longitude
  address: string;

  constructor(
    private geolocation: Geolocation,
    private nativeGeocoder: NativeGeocoder
  ) {}

  // geolocation options
  options = {
    timeout: 10000, 
    enableHighAccuracy: true, 
    maximumAge: 3600
  };

  // use geolocation to get user's device coordinates
  getCurrentCoordinates() {
    this.geolocation.getCurrentPosition().then((resp) => {
      console.log(resp)
      this.latitude = resp.coords.latitude;
      this.longitude = resp.coords.longitude;
      this.getAddress(this.latitude, this.longitude);
     }).catch((error) => {
       console.log('Error getting location', error);
     });
  }

  // geocoder options
  nativeGeocoderOptions: NativeGeocoderOptions = {
    useLocale: true,
    maxResults: 5
  };

  // get address using coordinates
  getAddress(lat,long){
    this.nativeGeocoder.reverseGeocode(lat, long, this.nativeGeocoderOptions)
    .then((res: NativeGeocoderResult[]) => {
      this.address = this.pretifyAddress(res[0]);
    })
    .catch((error: any) => {
      alert('Error getting location'+ JSON.stringify(error));
    });
  }

  // address
  pretifyAddress(address){
    let obj = [];
    let data = "";
    for (let key in address) {
      obj.push(address[key]);
    }
    obj.reverse();
    for (let val in obj) {
      if(obj[val].length)
      data += obj[val]+', ';
    }
    return address.slice(0, -2);
  }
}

We defined address variable, then injected the NativeGeocoder API in the constructor.

The getAddress() method takes lat and long parameter, inside the function the reverseGeocode API provides reverseGeocode method that takes lat, long and nativeGeocoderOptions parameters and returns the address array. That raw address data is being filtered by pretifyAddress() method and returning comma separated address.

Add Target Platform: Android, iOS or Windows

Following code works best with the real device, so in the next step we will learn to add target platforms such as iOS, Android and Windows to check our code.

Add iOS Target Platform

ionic platform add ios

Add Android Target Platform

ionic platform add android

Add Windows Target Platform

ionic platform add windows

Build Your Ionic App

Use the following commands to build your Ionic app for various platforms:

ionic build ios
ionic build android
ionic build windows

Conclusion

Finally, Ionic 5 Cordova Geolocation and Geocoder plugins tutorial has been over. In this tutorial we have learned how to:

  • Set up a basic Ionic app from scratch.
  • Install and configure Cordova Geolocation and Geocoder Plugins in Ionic app.
  • Locate Current Location Latitude and Longitude.
  • Get Current User Address.
  • Add Target Platforms.
  • Build Ionic App.

Digamber
Digamber

Digamber Rawat is from Dev Bhoomi Uttarakhand, located in northwestern part of India. He is a Data Scientist by profession and a primary author of this blog.