How to Switch on Device GPS in Ionic 6 without Leaving App

Last updated on: by Digamber

Imagine you are working on something important, and suddenly you need to turn on the Device GPS. Often you have to go away from your application and land on the setting section to turn on your device’s GPS.

What if you can turn on the device GPS without even leaving your application.

We will share with you how you can enable your mobile’s GPS without leaving; it will remain your interest intact and save your time.

Throughout this step by step guide, you will learn how to switch on the device GPS without even leaving the application using Ionic Native & Cordova plugins Android Permissions, Location Accuracy, and Geolocation.

Create New Ionic Project

Ionic CLI is an essential tool for creating a new Ionic application:

npm install -g @ionic/cli

Next, create a new Ionic Angular project:

ionic start ionic-gps-app blank --type=angular

Arrive inside the project:

cd ionic-gps-app 

Install Cordova Plugin

Turning on the device GPS requires three plugins to be installed in an Ionic app; open your console:

The Android permissions plugins allow you to deal with permissions; it opens the dialogue with deny and allows buttons; apparently, you have to install this module to get permission for Geolocation.

ionic cordova plugin add cordova-plugin-request-location-accuracy
npm install @ionic-native/location-accuracy
npm i @ionic-native/core

The Location Accuracy plugin pops up a model and asks for turning on the GPS without heading to the setting section.

ionic cordova plugin add cordova-plugin-request-location-accuracy
npm install @ionic-native/location-accuracy

On top of that, the Cordova & ionic native geolocation plugin gets the device geolocation coordinates.

ionic cordova plugin add cordova-plugin-geolocation
npm install @ionic-native/geolocation

Import Cordova Plugins in AppModule Class

Now that you have to import these plugins in the application’s main app.module.ts file, even more, inject theme inside the providers‘ array within AppModule class.

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';
// cordova plugins
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    AndroidPermissions,
    LocationAccuracy,
    Geolocation,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

Turn on Ionic 6 Device GPS

Add below code in home.page.ts component file:

// home.page.ts
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 {
  locCords: any;
  times: any;
  constructor(
    private androidPermissions: AndroidPermissions,
    private geolocation: Geolocation,
    private locationAccuracy: LocationAccuracy
  ) {
    this.locCords = {
      latitude: "",
      longitude: "",
      accuracy: "",
      timestamp: ""
    }
    this.times = Date.now();
  }
  chckAppGpsPermission() {
    this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
      result => {
        if (result.hasPermission) {
          this.requestToSwitchOnGPS();
        } else {
          this.askGPSPermission();
        }
      },
      err => {
        alert(err);
      }
    );
  }
  askGPSPermission() {
    this.locationAccuracy.canRequest().then((canRequest: boolean) => {
      if (canRequest) {
      } else {
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
          .then(
            () => {
              this.requestToSwitchOnGPS();
            },
            error => {
              alert(error)
            }
          );
      }
    });
  }
  requestToSwitchOnGPS() {
    this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
      () => {
        this.getLocationAccCords()
      },
      error => alert(JSON.stringify(error))
    );
  }
  getLocationAccCords() {
    this.geolocation.getCurrentPosition().then((response) => {
      this.locCords.latitude = response.coords.latitude;
      this.locCords.longitude = response.coords.longitude;
      this.locCords.accuracy = response.coords.accuracy;
      this.locCords.timestamp = response.timestamp;
    }).catch((err) => {
      alert('Error: ' + err);
    });
  }
}

The chckAppGpsPermission() function makes sure if your application is allowed to access device coordinates.

Notwithstanding, if permission hasn’t been given, then the askGPSPermission() function asks for the users’ device location.

Anyhow if location permission is already turned on, then the requestToSwitchOnGPS() function will display the dialog, which will turn on the device GPS even without leaving from the application.

Add below code in home.page.html component file:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Turn on Ionic Device GPS
    </ion-title>
  </ion-toolbar>
</ion-header>
<ion-content [fullscreen]="true">
  <div id="container">
    <ion-button color="danger" (click)="chckAppGpsPermission()">
      Get GPS Locaction
    </ion-button>
    <ion-row>
      <ion-col>Longitude</ion-col>
      <ion-col> {{locCords.longitude}}</ion-col>
    </ion-row>
    <ion-row>
      <ion-col>Latitude</ion-col>
      <ion-col>{{locCords.latitude}}</ion-col>
    </ion-row>
    <ion-row>
      <ion-col>Accuracy</ion-col>
      <ion-col>{{locCords.accuracy}}</ion-col>
    </ion-row>
    <ion-row>
      <ion-col>Timestamp</ion-col>
      <ion-col>{{locCords.timestamp | date:'medium'}}</ion-col>
    </ion-row>
  </div>
</ion-content>

Test Application

In this last step, you have to add platform:

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

Next, run following command to create runnable build:

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

Start the app in the virtual or real device.

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

Summary

As you can see, it was easy to turn on the device GPS with the help of a simple method without even leaving the ionic application. I hope you have got the answer.

You know how to easily enable your device’s GPS service with the help of Ionic Geolocation services even more without going away from the application.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.