How to Switch on Device GPS in Ionic 7 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:

sudo npm install -g @ionic/cli

Next, create a new Ionic Angular project:

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

Get inside the project:

cd ionic-gps-app 

Run the below command to add the native core package.

npm install @ionic-native/core --legacy-peer-deps

Disable Strict Type Errors

To avoid TypeScript compiling issues, we just need to open tsconfig.json file:

First, set below property under “compilerOptions” property.

"compilerOptions": {
    "strictPropertyInitialization": false,
    "skipLibCheck": true
    ...
}

Secondly, add given props under “angularCompilerOptions”.

"angularCompilerOptions": {
    "strictTemplates": false,
    ...
}

Install Cordova Plugins

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.

npm i cordova-plugin-request-location-accuracy --legacy-peer-deps
npm install @ionic-native/location-accuracy --legacy-peer-deps

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

npm i cordova-plugin-request-location-accuracy --legacy-peer-deps
npm install @ionic-native/location-accuracy --legacy-peer-deps

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

npm i cordova-plugin-geolocation --legacy-peer-deps
npm install @ionic-native/geolocation --legacy-peer-deps

Let’s install Android Permissions library, this package is developer to support Android new permissions checking mechanism.

npm install cordova-plugin-android-permissions --legacy-peer-deps
npm install @awesome-cordova-plugins/android-permissions --legacy-peer-deps
ionic cap sync

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

Turn on Ionic 7 Device GPS

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

import { Component } from '@angular/core';
import { AndroidPermissions } from '@awesome-cordova-plugins/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.

positronX.io - Tamso Ma Jyotirgamaya
Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.