In this tutorial, we’ll learn Ionic Capacitor Geolocation for getting location data latitude and longitude. The Geolocation API of Capacitor provides simple methods for getting and tracking the current position of the device using GPS, along with altitude, heading, and speed information if available. For building a Progressive Web Application (PWA) we need to use a Capacitor to implement a Geolocation feature that shows the current geographical location of the user.
In this tutorial, we’ll learn how to add the Capacitor Geolocation plugin and demonstrate how to get geolocation latitude and longitude cooridnate. We’ll also add a watch location to get the current position of geolocation.
Prerequisites:
To create and run an Ionic project, We need Nodejs and Ionic CLI already install in our system, if not then check how to install Nodejs and Ionic in Ubuntu. Ionic CLI allows us to create an Ionic project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install the Ionic CLI, open a terminal, and run the following command:
npm install -g @ionic/cli
Setting up and configuring Ionic capacitor geolocation project
Let’s first create an Ionic angular project to implement a capacitor geolocation plugin. We’ll create a blank Ionic Angular template. Here is a screenshot of our Ionic capacitor geolocation example.
Step 1: Create a project for Capacitor Geolocation
ionic start geolocationApp blank --type=angular
cd geolocationApp
When creating a new project from the ionic CLI command line it will install a capacitor along with creating a project.
Step 2: Install capacitor geolocation plugin
npm install @capacitor/geolocation
npx cap sync
When running the second command capacitor sync, it may show an error, this is because we have not yet built the application. We can build an application by running npm run build which will create a www folder and solve errors if they happen.
Step 3: Add platform and setting capacitor permissions example
Let first add the Android platform to our project by running the following commands.
npm install @capacitor/android
npx cap add android
We can add other platforms by running the same methods.
$npx cap add ios
$npx cap add electron
Once we had added the platform, for Android we need to add permission to use the Geolocation plugin. In the Android/app/src/main/AndroidManifest.xml
<!-- Geolocation API -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
Step 4: In the home.page.ts file, we will add 3 methods, one to get the current coordinate, and another method to get the changed coordinate.
import { Component, NgZone } from '@angular/core';
import { CallbackID, Capacitor } from '@capacitor/core';
import { Geolocation } from '@capacitor/geolocation';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
coordinate: any;
watchCoordinate: any;
watchId: any;
constructor(private zone: NgZone) { }
async requestPermissions() {
const permResult = await Geolocation.requestPermissions();
console.log('Perm request result: ', permResult);
}
getCurrentCoordinate() {
if (!Capacitor.isPluginAvailable('Geolocation')) {
console.log('Plugin geolocation not available');
return;
}
Geolocation.getCurrentPosition().then(data => {
this.coordinate = {
latitude: data.coords.latitude,
longitude: data.coords.longitude,
accuracy: data.coords.accuracy
};
}).catch(err => {
console.error(err);
});
}
watchPosition() {
try {
this.watchId = Geolocation.watchPosition({}, (position, err) => {
console.log('Watch', position);
this.zone.run(() => {
this.watchCoordinate = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
};
});
});
} catch (e) {
console.error(e);
}
}
clearWatch() {
if (this.watchId != null) {
Geolocation.clearWatch({ id: this.watchId });
}
}
}
Step 5: In the template of home.page.html, we have a button to display coordinates as
<ion-header>
<ion-toolbar>
<ion-title>
Capacitor Geolocation
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<ion-button size="small" (click)="requestPermissions()">
Geolocation Permissions
</ion-button>
<ion-card>
<ion-card-header>
<ion-button size="small" (click)="getCurrentCoordinate()">
Current Coordinate
</ion-button>
</ion-card-header>
<ion-card-content>
Lat: {{coordinate?.latitude }}
Long:{{ coordinate?.longitude }}
</ion-card-content>
</ion-card>
<ion-card>
<ion-card-header>
<ion-button size="small" (click)="watchPosition()">
Watch Position
</ion-button>
</ion-card-header>
<ion-card-content>
Lat: {{watchCoordinate?.latitude }}
Long: {{ watchCoordinate?.longitude }}
</ion-card-content>
</ion-card>
<ion-button size="small" (click)="clearWatch()">Clear Watch</ion-button>
</ion-content>
To check more information on ionic capacitor Geolocation on the official documentation link.
Related posts
- How to set up a capacitor in an Ionic project.
- Ionic Capacitor camera example
- Ionic capacitor storage
- Ionic network detection with Capacitor