You've successfully subscribed to Smartcodehub ™ Blog
Great! Next, complete checkout for full access to Smartcodehub ™ Blog
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Ionic 5 | Geolocation

Ionic 5 | Geolocation

How to implement geolocation in ionic 5 capacitor blank project, it can easily be done with geolocation plugin in ionic, also learn to implement androidPermission in ionic 5.

Abhishek Dana
Abhishek Dana

Hello there, today in this blog we are going to see how we can access user location with the help of Geolocation Plugin capacitor in ionic 5.With the geolocation we can get user current position which might help a developer when we make apps for delivery services, tracking services etc.

Today we will learn about how to implement geolocation in ionic 5 blank project.But before starting let's see the official documentation of capacitor geolocation plugin and methods provided by them over here.

Simple implementation of Geolocation Plugin to demonstrate methods..

import { Plugins } from '@capacitor/core';

const { Geolocation } = Plugins;

class GeolocationExample {
  async getCurrentPosition() {
    const coordinates = await Geolocation.getCurrentPosition();
    console.log('Current', coordinates);
  }

  watchPosition() {
    const wait = Geolocation.watchPosition({}, (position, err) => {
    })
  }
}

Here the getCurrentPosition method with get the current location of the user in application by accessing the geolocation services of smartphone using capacitor, the method used to get current location is Geolocation.getCurrentPosition() which return the user coordinates i.e longitude and latitude with the help of coordinates we can use google map or any other services to get address of the user also to show the marker on google map we need coordinates so we can use this coords according to our need.

WatchPosition in geolocation help us to get the real time position of user basically we can track user motion with the help of watchPosition which again returns the same coordinates of user in format of json with properties of longitude and latitude in perticular amount of time.

stopWatchPosition() {
	Geolocation.clearWatch();
}

To Stop watching/tracking the user location we simply need to call method Geolocation.clearWatch which will clear user location access untill user again want to share according to his/her need.

There are some options available while using getCurrentPosition() method

const option = {
	enableHighAccuracy ?: boolean;
	maximumAge ?: number;
	timeout ?: number;
}

Which lets you get accurate location of user for perticular time and the amount of stay also.

Now to implement Geolocation we need to make a blank ionic project with Capacitor

So let's get started

ionic start geoTracker

After successfully generating the ionic project open the project in code editor and head over to integrated terminal and excute the above commands. First we need to install androidPermission plugin to get location access from user.

npm install cordova-plugin-android-permissions

npm install @ionic-native/android-permissions

ionic cap sync

Second we need to install geolocation capacitor plugin in our project.

// Installing the cordova geolocation plugin 
npm install cordova-plugin-geolocation

// Install NPM package for geolocation
npm install @ionic-native/geolocation

// Linking Cordova Plugin to Capacitor
ionic cap sync

After installation open app.module.ts and import the geolocation and androidPermission Provider.

import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';

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

Now head over to home.page.ts file and write a method to get location Permission and call it on ngOnInit method..

 checkGPSPermission() { 			   this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
      result => {
        if (result.hasPermission) {
          this.getUserPosition();
        } else {
          this.requestLocationPermission();
        }
      },
      err => {
        alert(err);
      }
    );
  }

The above method will first check if user have give location access permission to application if yes then it will get user location else it should prompt user to ask location access.

// Requesting User Location

requestLocationPermission() { this.androidPermissions.requestPermissions(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
      result => {
        if (result.hasPermission) {
          this.getUserPosition();
        } else {
          alert("User Deny Location Access Permission")
        }
      },
      err => {
        alert(err);
      }
    );

}

Now after requesting Permission we need to get User Position that can be easily done by using Geolocation.getCurrentPosition method.

getUserPosition() {
	 const coordinates = await Geolocation.getCurrentPosition();
     console.log('Current', coordinates);
}

🎉 Hurray 🎉,  we have successfully implemented Geolocation In our ionic project you can now simply build application and run it on your devices and get your location.

That's it for this blog. Stay Tuned 🤓 for more blog....