Ionic 6 Angular Geolocation and Geocoder Integration Tutorial

Ionic Angular Geolocation tutorial; In this tutorial, you will integrate Geolocation in the Ionic app to get the device information using latitude and longitude using the Geolocation and Native Geocoder plugin.

In this profound Ionic geolocation example, we will share how to get an address from latitude and longitude in the ionic apps.

Additionally, you will use the ionic reverse geocoding concept; for handling reverse geocoding, we will add a native geocoder plugin.

It is basically a handy method to access reverseGeocode() method pass latitude and longitude as a parameter and get the user’s physical address.

Geolocation API is a boon and works marvellously great; you can get device location information, latitude and longitude, you can play with location information which includes GPS.

Plus, you can deal with location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs.

How to Add Geolocation and Geocoder in Ionic 6

  • Step 1: Set Up Ionic App
  • Step 2: Install Geolocation and Geocoder Packages
  • Step 3: Add Geolocation and Geocoder in AppModule
  • Step 4: Get Geolocation Information
  • Step 5: Run Ionic Application

Set Up Ionic App

Ionic app installation is only possible if you have Ionic CLI installed on the development system, so go ahead with the given below command:

npm install -g @ionic/cli

Get started with Ionic angular app installation using the recommended command:

ionic start demo-app blank --type=angular

Next, head over to app folder:

cd demo-app

Remove Type Errors

You have to remove strict type errors make sure to set “strictTemplates”: false in angularCompilerOptions in tsconfig.json file.

Install Geolocation and Geocoder Plugins

This step quickly tells you how to add geolocation, native geocoder and ionic native core plugins into the ionic, angular app.

Ionic native core: Ionic Native is a TypeScript wrapper for Cordova/PhoneGap plugins that helps in adding any native functionality, which makes the Ionic mobile app development facile.

ionic cordova plugin add cordova-plugin-geolocation

npm install @ionic-native/geolocation

npm i @ionic-native/core

Add or install a native geocoder package, which is a Cordova plugin for native forward and reverse geocoding.

ionic cordova plugin add cordova-plugin-nativegeocoder

npm install @ionic-native/native-geocoder

For iOS you have to add this configuration to your configuration.xml file

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

Add Geolocation and Geocoder in AppModule

To get address information from latitude and longitude, you need to access several methods offered by Geolocation and NativeGeocoder packages. For doing that, you have to register both the plugins into the ionic main app module class.

Update app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';


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



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

export class AppModule {}

Get Geolocation Information

The geoInformation() method allows you to access the getCurrentPosition() method returns a promise that lets you get the current location’s latitude, longitude, accuracy and other information related to geolocation.

The nativeGeocoder provides a reverse geocode method, which takes location coordinates such as latitude and longitude along with native geocoder options. It returns a promise to get the physical address of the location with a native geocoder.

The createAddress() method filters out the address and shows the physical address of the location.

Place below code and update home.page.ts file:

import { Component } from '@angular/core';

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

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

export class HomePage {
  lat: any; 
  long: any;
  address: any;
  accuracy: any;

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

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

  geoInformation() {
    this.geolocation.getCurrentPosition().then((data) => {
      this.lat = data.coords.latitude;
      this.long = data.coords.longitude;
      this.accuracy = data.coords.accuracy;

      this.cordsToAddress(this.lat, this.long);
     }).catch((error) => {
       alert(error);
     });
  }

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

  // reverse geocode
  cordsToAddress(lat, long){
    this.nativeGeocoder.reverseGeocode(lat, long, this.nativeGeocoderOptions)
    .then((response: NativeGeocoderResult[]) => {
      this.address = this.createAddress(response[0]);
    }).catch((error: any) => {
      alert(JSON.stringify(error));
    });
  }

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

The geoInformation() function should be added to click event, which displays latitude, longitude, address and accuracy on the home page.

Place below code and update home.page.html file:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Geolocation Demo
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-button (click)="geoInformation()" color="danger">
    Get Device Location
  </ion-button>

  <ion-item>
    <strong>Location Information</strong>
  </ion-item>

  <ion-item>
    <ion-label>Latitue</ion-label>
    <ion-badge color="secondary">{{lat}}</ion-badge>
  </ion-item>

  <ion-item>
    <ion-label>Longitude</ion-label>
    <ion-badge color="tertiary">{{long}}</ion-badge>
  </ion-item>

  <ion-item>
    <strong>Address</strong>
  </ion-item>

  <ion-item>
    {{ address }}
  </ion-item>  

  <ion-item>
    <ion-label><strong>Accuracy</strong></ion-label>
    <ion-badge>{{ accuracy }}</ion-badge>
  </ion-item>
</ion-content>

Run Ionic Application

Lastly, to check the app, open the console, try running add, create build, and serve the application on a real or virtual device.

# iOS
ionic cordova platform add ios

# Android
ionic cordova platform add android

# Windows
ionic cordova platform add windows

Afterwards, execute suggested command to create a build:

# iOS
ionic cordova build ios

# Android
ionic cordova build android

# Windows
ionic cordova build windows

Then, run the application:

# iOS
ionic cordova run ios -l

# Android
ionic cordova run android -l

# Windows
ionic cordova run windows -l

Ionic get geo location information

Conclusion

The ionic native geocoder tutorial is over; throughout this exclusive ionic geolocation example, we understood adding Geolocation, Geolocation plugin into ionic app.

Moreover, we have learned how to get the current address based on latitude and longitude, device accuracy and also get device coordinates in ionic.