Ionic 5|4 Geolocation, Native Geocoder Example Pincode Application to get Coordinates and Address

In this Ionic 5 tutorial, we’ll discuss how to add Geolocation functionality to get current location in the form of coordinates like latitude, longitude and accuracy of the device. Also, we’ll add the Geocoder plugin in the application to convert coordinates into a readable physical address. Fetching location of a device plays a great role…

By.

•

min read

In this Ionic 5 tutorial, we’ll discuss how to add Geolocation functionality to get current location in the form of coordinates like latitude, longitude and accuracy of the device. Also, we’ll add the Geocoder plugin in the application to convert coordinates into a readable physical address.

Fetching location of a device plays a great role in a number of real-world applications around us. In one or the other task, we may need coordinates, for example, to deliver some items, book a cab, check the weather at the current location etc.

Hybrid Application we can easily access native features of a device using Cordova plugin and Native wrappers for Ionic Framework. We’ll create an example Ionic 5 application and implement Geolocation service to get Lattitude, Longitude, Accuracy of location, Speed, Altitude etc of the device. After we have Latitude and Longitude, these can be used to get Addresses available on these coordinates. To fetch address from coordinates of the device, we use Geocoder service.

So, let’s begin …

 

Also Check: Ionic 4 | Turn on Device GPS in Ionic 4 Application Without Leaving App

 

Update Ionic CLI

We are going to build an Ionic application in using the latest version of the @ionic/cli package which is 6.7.0. You can update by running below npm command in the terminal

$ npm install -g @ionic/cli</pre>
 
<h3>Create New Ionic 5 application.</h3>
After updating the Ionic CLI, execute below ionic command to create a new Ionic application using Angular framework by adding the <code>--type=angular option with a blank template.
$ ionic start ionic-geolocation-geocoder-application blank --type=angular</pre>
move to the application folder
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd ionic-geolocation-geocoder-application</pre>
If you have Visual Studio Code installed, open the product by running the following command
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ code .</pre>
 
<h3>How to Install Geolocation, Geocoder Cordova and Native Plugins in Ionic App</h3>
In this step, we'll install Cordova plugins for Geolocation, Geocoder and then configure to use Native wrappers for Ionic 5 Angular application.

 

<strong>Geolocation</strong>

Install Cordova and Ionic Native plugins by running following command in the terminal at the application root
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install @ionic-native/geolocation</pre>
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.

This plugin is supported for following OS-based devices:
<ul>
 	<li>Android</li>
 	<li>iOS</li>
 	<li>Windows OS Based Apps</li>
 	<li>Browser Application</li>
 	<li>Amazon Fire OS</li>
</ul>
<p class="intro">If using for iOS, you have to add this configuration to your <code>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>

 

Native Geocoder

The Native Geocoder plugin provides services to convert a given coordinate into address also it helps in native forward and reverse geocoding. This plugin is supported by Android and iOS devices.

Run the following command to install geocoder plugin for an Ionic application

$ ionic cordova plugin add cordova-plugin-nativegeocoder
$ npm install @ionic-native/native-geocoder</pre>
 
<h3>Configure App Module to Import Plugins</h3>
Now import above plugins in the app module file to use its services, open the <strong>app.module.ts</strong> file, import the <code>Geolocation and NativeGeocoder class them add in the providers 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';

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,
    Geolocation,
    NativeGeocoder,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Get Device Current Location Coordinates and Address using Geolocation, Geocoder Plugins in Ionic Angular  Application

Many popular applications like UBER, Facebook, Zomato, Amazon gets user's device location to personalize and facilitate in a better way. These applications depend on the user location for a number of operations.

In Ionic application, the combination of these Cordova and Native plugins makes it very easy to get user device located in a few lines of code in javascript.

Let's check to get user location and fetch address in the Home Page of our Ionic application.

Open the home.page.ts file, then make the changes shown below

// home.page.ts
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 {

  // Readable Address
  address: string;

  // Location coordinates
  latitude: number;
  longitude: number;
  accuracy: number;

  //Geocoder configuration
  geoencoderOptions: NativeGeocoderOptions = {
    useLocale: true,
    maxResults: 5
  };
  constructor(
    private geolocation: Geolocation,
    private nativeGeocoder: NativeGeocoder
  ) {
  }


  //Get current coordinates of device
  getGeolocation() {
    this.geolocation.getCurrentPosition().then((resp) => {

      this.latitude = resp.coords.latitude;
      this.longitude = resp.coords.longitude;
      this.accuracy = resp.coords.accuracy;

      this.getGeoencoder(resp.coords.latitude, resp.coords.longitude);

    }).catch((error) => {
      alert('Error getting location' + JSON.stringify(error));
    });
  }

  //geocoder method to fetch address from coordinates passed as arguments
  getGeoencoder(latitude, longitude) {
    this.nativeGeocoder.reverseGeocode(latitude, longitude, this.geoencoderOptions)
      .then((result: NativeGeocoderResult[]) => {
        this.address = this.generateAddress(result[0]);
      })
      .catch((error: any) => {
        alert('Error getting location' + JSON.stringify(error));
      });
  }

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

}
</pre>
The <strong><code>getCurrentPosition() method available in the Geolocation class fetches the device coordinates including latitude, longitude, accuracy, speed, time and other information.

In the custom getGeoencoder() method we are passing the latitude and longitude which in turn calling the reverseGeocode method available in the NativeGeocoder class. We also passed the configuration object of type NativeGeocoderOptions to set a number of nearby address based on coordinates supplied.

The reverseGeocode() method returns a bit non-readable array including address data, which we are passing to a custom method generateAddress() method, which saved the readable comma separated string in the address variable.

 


Also, check Geolocation & Geocoder plugins with Javascript API Google Maps in Ionic 5 Application.
       
  In home.page.html, add following HTML
<ion-header [translucent]="true">
  <ion-toolbar color="secondary">
    <ion-title>
      Cordinates & Address in Ionic App
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">

  <h4>Geolocation & Gecoder App</h4>

  <ion-grid>

    <!-- Latitude -->
    <ion-row>
      <ion-col size="4" class="ion-text-center">
        Latitue
      </ion-col>
      <ion-col>
        <ion-badge class="ion-text-wrap" color="medium">{{latitude}}</ion-badge>
      </ion-col>
    </ion-row>

    <!-- Longitude -->
    <ion-row>
      <ion-col size="4" class="ion-text-center">
        longitude
      </ion-col>
      <ion-col>
        <ion-badge class="ion-text-wrap" color="medium">{{longitude}}</ion-badge>
      </ion-col>
    </ion-row>

    <!-- Accuracy -->
    <ion-row>
      <ion-col size="4" class="ion-text-center" color="medium">
        Accuracy
      </ion-col>
      <ion-col>
        <ion-badge class="ion-text-wrap" color="medium">{{accuracy}}</ion-badge>
      </ion-col>
    </ion-row>

    <!-- Address -->
    <ion-row>
      <ion-col size="4" class="ion-text-center">
        Address
      </ion-col>
      <ion-col>
        <ion-badge class="ion-text-wrap" color="medium">{{address}}</ion-badge>
      </ion-col>
    </ion-row>

  </ion-grid>

  <ion-button (click)="getGeolocation()" color="success" expand="full">Get Location</ion-button>

</ion-content></pre>
In the HTML template, we used <code>ion-grip component with ion-badge to display the coordinates and address in an aligned format.

The button is calling the custom getGeolocation() method we defined in the class.

We are done with the implementation let's check how to run the application in the real device as NativeGeocoder service only works in the presence of Cordova.

 



 

Add OS Platform for Ionic Application

To create a build of the Ionic application to install in a real device, we need to add a target platform in our Ionic application. Run following commands to add a platform for Ionic 5 application
# For Android
$ ionic cordova platform add android

# For iOS
$ ionic cordova platform add ios

# For Windows
$ ionic cordova platform add windows

 

Build Ionic 5 Application

After adding the required platforms, we need to create a build by running following command for each platform.

# Android Build
$ ionic cordova build android

# iOS Build
$ ionic cordova build ios

# Windows Build
$ ionic cordova build windows

 

Test Run Your App on Device

You can move you build file from above command to your device or run the following command after connecting your Device with computer via USB cable.

# Run Android App
$ ionic cordova run android -l

# Run iOS App
$ ionic cordova run ios -l

# Run Windows App
$ ionic cordova run windows -l

 

Conclusion: That's it now we have an Ionic 5 application with Geolocation and Native Geocoder plugins installed. We can now fetch the user's device location coordinates and convert them into readable Address using Geocoder service. Also, we discussed how to add a platform then build a source file to test it in a real device.

 

Happy coding 🙂

24 responses to “Ionic 5|4 Geolocation, Native Geocoder Example Pincode Application to get Coordinates and Address”

  1. Sneha Avatar
    Sneha

    •

    do you get the location when offline? Please reply

  2. Crist Avatar
    Crist

    •

    Hi,
    sorry but does anyone has this error too?

    ERROR in src/app/pages/main/main.page.ts(3,47): error TS2305: Module ‘”Z:/ionic/movieApp/node_modules/@ionic-native/native-geocoder/ngx/index”‘ has no exported member ‘NativeGeocoderReverseResult’.

    [ERROR] An error occurred while running subprocess ng.

    How to fix it?
    Thanks,
    Cris.

  3. louloulfx Avatar
    louloulfx

    •

    It works for IOS ?, i don’t have apple

  4. shyni s Avatar
    shyni s

    •

    Please help me .. what argument should i pass to getCurrentPosition() and watchPosition() method ..please reply .
    Iam using ionic 4

    1. WuAn Avatar
      WuAn

      •

      i have this issue too. I use getCurrentPositon but result {}.

  5. manzoor Avatar
    manzoor

    •

    Hi Freaky Jolly,

    I’m not able to import ‘NativeGeocoderReverseResult’,
    Attach for screenshot

  6. Leonardo Avatar
    Leonardo

    •

    boa tarde, é que ta dando um erro pra mim na pagina home.page.ts a importação do NativeGeocoderReverseResult ele fica com uma barra vermelha (
    import { NativeGeocoder,NativeGeocoderOptions,NativeGeocoderReverseResult } from ‘@ionic-native/native-geocoder/ngx’; )com isso não consigo usar ele no aplicativo, por favor preciso disso o mais rapido possivel, desde já muito obrigado

    1. Gian Michel Avatar

      Hi, to fix that is pretty simple, i have to test it, but i think it will works:
      instead of using NativeGeocoderReverseResult, use NativeGeocoderResult and NativeGeocoderResult[].

      What have happened is that this method has being agrouped with forwardResult inside GeocoderResult

  7. Asif Avatar
    Asif

    •

    Can you please help me? I have got the error mention below

    error ts2305 module has no exported member NativeGeocoderReverseResult

Leave a Reply

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