In this Ionic 5/4 tutorial, we’ll learn how to make a user enable the Geolocation service without leaving or minimizing the application. We’ll use a Native plugin to open a dialog from which a user can tap to switch on the Geolocation service.
In Ionic Application which is using Geolocation get device location coordinates like latitude and longitude may need more accuracy. Device Geolocation service can location coordinates using the network, WiFi Bluetooth but for more accurate location device GPS option must be turned on, which can provide Location accuracy up to 10m which proves quite good for real-time and delivery applications.
In this post, we will discuss How to Turn on Device GPS option from Ionic Application itself, so that the user does not need to leave application. We will use Cordova and Ionic Native plugin, which will prompt the user to turn on GPS.
Version Check
@ionic/cli _ _ (_) ___ _ __ (_) ___ | |/ _ \| '_ \| |/ __| | | (_) | | | | | (__ |_|\___/|_| |_|_|\___| CLI 6.4.1 #Update to the latest version of Ionic CLI by running following NPM command: $ npm install -g @ionic/cli
Let’s get started!
Create a new Ionic Application
Execute following NPM command to create a new Angular Ionic application with a blank
template
$ ionic start IonicAccurateLocation blank --type=angular
$ cd IonicAccurateLocation
Install Plugins for Application
After creating the application, install three native plugins to help in providing more user-friendly behavior.
1) cordova-plugin-android-permissions
: Get permissions by showing the permission dialogue. We will use this plugin to get Geolocation access permission, but this can be used for any type of permission.
$ ionic cordova plugin add cordova-plugin-android-permissions
$ npm install @ionic-native/android-permissions
2) cordova-plugin-request-location-accuracy
: Shows a dialogue to the user to turn on GPS we show in the image below so that the user does not need to leave the app or go to setting.
$ ionic cordova plugin add cordova-plugin-request-location-accuracy
$ npm install @ionic-native/location-accuracy
3) cordova-plugin-geolocation
: Finally, after getting location access permission and turning on device GPS, we will fetch accurate device Geolocation coordinates using this Geolocation plugin.
$ ionic cordova plugin add cordova-plugin-geolocation
$ npm install @ionic-native/geolocation
Next, we need to inject these plugin in the app.module.ts file then add in the providers
array
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 { AndroidPermissions } from '@ionic-native/android-permissions/ngx'; import { Geolocation } from '@ionic-native/geolocation/ngx'; import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule], providers: [ StatusBar, SplashScreen, AndroidPermissions, Geolocation, LocationAccuracy, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule {}
Now we will use these in the application’s home component. In the home.component.ts file, we will add the following methods.
Check if the application is having permission to access device location by calling below method checkGPSPermission()
//Check if application having GPS access permission
checkGPSPermission() {
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
result => {
if (result.hasPermission) {
//If having permission show 'Turn On GPS' dialogue
this.askToTurnOnGPS();
} else {
//If not having permission ask for permission
this.requestGPSPermission();
}
},
err => {
alert(err);
}
);
}
If not then we will call the requestGPSPermission()
method to get location permission on the fly from the user.
requestGPSPermission() {
this.locationAccuracy.canRequest().then((canRequest: boolean) => {
if (canRequest) {
console.log("4");
} else {
//Show 'GPS Permission Request' dialogue
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
.then(
() => {
// call method to turn on GPS
this.askToTurnOnGPS();
},
error => {
//Show alert if user click on 'No Thanks'
alert('requestPermission Error requesting location permissions ' + error)
}
);
}
});
}
If the application is having location access permission then we will call the askToTurnOnGPS()
method. This is the method for which we are here 😛 this show GPS turn on dialogue in application
askToTurnOnGPS() {
this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
() => {
// When GPS Turned ON call method to get Accurate location coordinates
this.getLocationCoordinates()
},
error => alert('Error requesting location permissions ' + JSON.stringify(error))
);
}
After the user successfully turns on GPS then we will call getLocationCoordinates()
method to get an accurate location of the device.
// Methos to get device accurate coordinates using device GPS
getLocationCoordinates() {
this.geolocation.getCurrentPosition().then((resp) => {
this.locationCoords.latitude = resp.coords.latitude;
this.locationCoords.longitude = resp.coords.longitude;
this.locationCoords.accuracy = resp.coords.accuracy;
this.locationCoords.timestamp = resp.timestamp;
}).catch((error) => {
alert('Error getting location' + error);
});
}
After adding the above methods our complete home.component.ts file will look like this
import { Component } from '@angular/core';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss']
})
export class HomePage {
locationCoords: any;
timetest: any;
constructor(
private androidPermissions: AndroidPermissions,
private geolocation: Geolocation,
private locationAccuracy: LocationAccuracy
) {
this.locationCoords = {
latitude: "",
longitude: "",
accuracy: "",
timestamp: ""
}
this.timetest = Date.now();
}
//Check if application having GPS access permission
checkGPSPermission() {
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
result => {
if (result.hasPermission) {
//If having permission show 'Turn On GPS' dialogue
this.askToTurnOnGPS();
} else {
//If not having permission ask for permission
this.requestGPSPermission();
}
},
err => {
alert(err);
}
);
}
requestGPSPermission() {
this.locationAccuracy.canRequest().then((canRequest: boolean) => {
if (canRequest) {
console.log("4");
} else {
//Show 'GPS Permission Request' dialogue
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
.then(
() => {
// call method to turn on GPS
this.askToTurnOnGPS();
},
error => {
//Show alert if user click on 'No Thanks'
alert('requestPermission Error requesting location permissions ' + error)
}
);
}
});
}
askToTurnOnGPS() {
this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
() => {
// When GPS Turned ON call method to get Accurate location coordinates
this.getLocationCoordinates()
},
error => alert('Error requesting location permissions ' + JSON.stringify(error))
);
}
// Methos to get device accurate coordinates using device GPS
getLocationCoordinates() {
this.geolocation.getCurrentPosition().then((resp) => {
this.locationCoords.latitude = resp.coords.latitude;
this.locationCoords.longitude = resp.coords.longitude;
this.locationCoords.accuracy = resp.coords.accuracy;
this.locationCoords.timestamp = resp.timestamp;
}).catch((error) => {
alert('Error getting location' + error);
});
}
}
In the Home component’s HTML template we will just have a button which will call the checkGPSPermission
method which we added in ts file above and also show Geolocation Coordinates received back.
<ion-grid fixed>
<ion-row>
<ion-col text-center>
<ion-button (click)="checkGPSPermission()">
Request GPS Accuracy
</ion-button>
</ion-col>
</ion-row>
<ion-row>
<ion-col size="4">Longitude</ion-col>
<ion-col> {{locationCoords.longitude}}</ion-col>
</ion-row>
<ion-row>
<ion-col size="4">Latitude</ion-col>
<ion-col>{{locationCoords.latitude}}</ion-col>
</ion-row>
<ion-row>
<ion-col size="4">Accuracy</ion-col>
<ion-col>{{locationCoords.accuracy}}</ion-col>
</ion-row>
<ion-row>
<ion-col size="4">Timestamp</ion-col>
<ion-col>{{locationCoords.timestamp | date:'medium'}}</ion-col>
</ion-row>
</ion-grid>
That’s it, in the above tutorial we got to know How to get user device Geolocation permission with more accuracy by turning on device GPS after providing Geolocation permission to an application.
Conclusion: In this tutorial, we discussed How to use Geolocation services in Ionic application and providing a user more convenience to enable GPS service on the device from without leaving the application.
Leave a Reply