HI WELCOME TO Sirees

Ionic 6 Cordova Geolocation and Geocoder Tutorial

Leave a Comment

 Ionic 6 Angular Geolocation and Geocoder tutorial; This is a step by step tutorial on how to use Cordova Geolocation and Geocoder plugin in an Ionic 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.

Ionic 6 Angular Get Geolocation Example

  • Step 1: Prerequisite
  • Step 2: Create New Ionic Angular Project
  • Step 3: Install & Configure Cordova Geolocation and Geocoder Plugins
  • Step 4: Get Current Location Latitude and Longitude
  • Step 5: Get Current Address
  • Step 6: Start Ionic App

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 Cordova globally on your machine.

sudo npm install -g cordova ionic
Bash

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

ionic -v
Bash

Use below command to update Ionic and Cordova.

sudo npm update -g cordova ionic
Bash

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
Bash

Get inside the project folder.

cd ionic-geolocation-app
Bash

Start the app in the browser.

ionic serve --lab
Bash

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 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
Bash

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

npm install @ionic-native/geolocation
React JSX

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>
React JSX

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
Bash

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.

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

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);
     });
  }
}
TypeScript

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 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>
Markup

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';
TypeScript

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);
  }
}
TypeScript

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.

Start Ionic App in Device

We will learn how to add target platforms for iOS, Android and Windows to test our app.

# iOS
ionic cordova platform add ios
# Android
ionic cordova platform add android
# Windows
ionic cordova platform add windows
Bash

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

# iOS
ionic cordova build ios
# Android
ionic cordova build android
# Windows
ionic cordova build windows
Bash

Start the app in the device.

# iOS
ionic cordova run ios -l
# Android
ionic cordova run android -l
# Windows
ionic cordova run windows -l
Bash

Conclusion

Finally, Ionic 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.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.