Ionic/Angular Turn on Device GPS Without Leaving Application using Native Plugin

In this Ionic/Angular tutorial, we'll learn how to make it so that a user can turn on the Geolocation service without leaving or shrinking the app. We'll use a Native plugin to open a dialogue where the user can tap to turn on the Geolocation service.

Ionic apps that use geolocation to get the location of a device's latitude and longitude may need to be more precise. The network, WiFi, and Bluetooth can be used by the device's geolocation service to find its coordinates, but for a more accurate location, the device's GPS option must be turned on. It can give a location accuracy of up to 10 meters, which is suitable for real-time and delivery applications.

In this post, we'll talk about how to turn on your device's GPS from within the Ionic app so you don't have to leave the app. We will use Cordova and the Ionic Native plugin, asking the user to turn on GPS.

Make a new Ionic 4/5 application.

Ionic CLI will be used to make a new app.

run the below command to install ionic globally

npm install -g ionic@latest cordova

After ensuring these are installed, run the command below to start a new Ionic 4/5 project. Don't forget to change name> to the name you wanted for your project.

ionic start <name> blank --type=angular --spec false

Install the Ionic Native Plugin & Cordova.

We will install the following android-permissions plugin.

AndroidPermission plugin Show the permission dialogue to get permissions. We'll use this plugin to access Geolocation, but it can be used to get any kind of permission.

Run these two commands in your favorite terminal to install AndroidPermission plugin:

ionic cordova plugin add cordova-plugin-android-permissions
npm install @ionic-native/android-permissions

this will install AndroidPermission plugin in our Ionic/Angular project. 

Cordova-plugin-request-location-accuracy: Displays a dialogue box that lets the user turn on GPS without leaving the app or going to settings.


Next, This part is important. Here we need to import the plugin and register in providers array. Open app.module.ts file & add the following changes.

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 {}

We will now use these in the home part of the app. We will add the following function to the home.component.ts file.

Check if the app is allowed to use the device's location by calling the checkGPSPermission() function below

 

 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 {
          this.requestGPSPermission();
        }
      },
      err => {
        alert(err);
      }
    );
  }

If not, we'll use the requestGPSPermission() method to ask the user for permission to use their location right away.
 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(
            () => {
              // Request to turn on GPS
              this.askToTurnOnGPS();
            },
            error => {
              // You can show alert when user click on 'No Thanks' button.
              alert(' Request Permission Error ' + error);
            }
          );
      }
    });
  }


We will call the askToTurnOnGPS() method if the application has permission to access location data. It shows the GPS on/off dialogue in the app.


 askToTurnOnGPS() {
    this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(() => {
        // Call the method to get accurate location coordinates when GPS is turned on.
        this.getLocationCoordinates()
      },
      err => alert('Error requesting GPS permissions ' + JSON.stringify(err));
    );
  }

After the user turns on GPS successfully, we will call the getLocationCoordinates() method to find out where the device is.

  // Function to use GPS to get accurate coordinates.
  getLocationCoordinates() {
    this.geolocation.getCurrentPosition().then((res) => {
      this.locationCoords.latitude = res.coords.latitude;
      this.locationCoords.longitude = res.coords.longitude;
      this.locationCoords.accuracy = res.coords.accuracy;
      this.locationCoords.timestamp = res.timestamp;
    }).catch((err) => {
      alert('Error getting location: ' + err);
    });
  }

After adding the above methods, our 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 = {};
  timetst: any;

  constructor(
    public androidPermission: AndroidPermissions,
    public geolocation: Geolocation,
    public locationAccuracy: LocationAccuracy
  ) {
    this.locationCoords = {
      latitude: '',
      longitude: '',
      accuracy: '',
      timestamp: ''
    }
    this.timetst = Date.now();
  }


  //Check if application having GPS access permission  
  checkGPSPermission() {
    this.androidPermission.checkPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
      res => {
        if (res.hasPermission) {

          // If you have permission, show the "Turn on GPS" screen.
          this.askToTurnOnGPS();
        } else {

          // If you don't have permission, request for it.
          this.requestGPSPermission();
        }
      },
      error => {
        alert(error);
      }
    );
  }

  requestGPSPermission() {
    this.locationAccuracy.canRequest().then((canRequest: boolean) => {
      if (canRequest) {
        console.log('4');
      } else {
        // Show the "GPS Permission Request" screen
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
          .then(
            () => {
              // function to turn on gps
              this.askToTurnOnGPS();
            },
            error => {
              // Alert to show when permission error occurs
              alert(' Request Permission Error: ' + error);
} ); } }); } askToTurnOnGPS() { this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(() => { // Function to get Accurate location coordinates this.getLocationCoordinates() }, err => alert('Error requesting location: ' + JSON.stringify(err)); ); } // Function to get device accurate coordinates with 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); }); } }

The HTML template for the Home component will only have a button. This button will call the checkGPSPermission() function which we added in .ts file above, and it will also show the Geolocation Coordinates.


<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 all there is to it. In the above tutorial, we learned How to get user device Geolocation permission more accurately by turning on the device's GPS after giving Geolocation permission to an application.


Conclusion

So, This is it for Ionic/Angular GPS location article. Subscribe us on YouTube for more.


Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !