How to Enable or Turn on GPS in Ionic 6 without Leaving App

How to enable GPS in Ionic without leaving the application, a great user experience is the key to success.

A user-friendly application doesn’t get created in one day; rather, it is developed gradually by taking care of even the smaller things.

In this Ionic GPS tutorial, we will help you learn how to turn on your device’s GPS (Global Positioning System) and that too, even without leaving the existing application.

Ideally, it becomes a little annoying when you have to follow the complete process when you have to pull out of the current app and head over to settings to switch on the GPS.

Nonetheless, we will make your life facile by creating a small feature in which you can switch on GPS in Ionic without leaving the app using Ionic native and Cordova plugins.

Install Ionic App

Verily, it is advisable to install the Ionic CLI tool for Ionic development:

npm install -g @ionic/cli

Type suggested command in the terminal to manifest a new Ionic Angular application:

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

Head over to application’s root:

cd ionic-demo-app 

Remove Type Errors

You have to remove strict type errors make sure to set “strictTemplates”: false in angularCompilerOptions in tsconfig.json file.

Install Ionic Native and Cordova Plugins

In this second step, you have to add android permission, location accuracy, and geolocation packages. Wherefore, execute all the recommended commands from terminal:

The Android permissions plugins is developed to enhance support for new permissions checking mechanism.

ionic cordova plugin add cordova-plugin-android-permissions

npm install @ionic-native/android-permissions

This is an exclusive plugin for Android and iOS for enabling the request of Location services by manifest a native dialog through the app, bypassing the requirement for the user to move away from your app to modify the location settings manually.

ionic cordova plugin add cordova-plugin-request-location-accuracy

npm install @ionic-native/location-accuracy

This plugin offers information regarding the device’s location, for instance, latitude and longitude. Conventional location information sources involve GPS and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs.

ionic cordova plugin add cordova-plugin-geolocation

npm install @ionic-native/geolocation

Update Ionic Native and Cordova Plugins in Main Module

In this third step, you require to import LocationAccuracy, Geolocation over and above that the AndroidPermissions, additionally register these three packages consecutively inside the providers’ array.

Open and update app.module.ts file:

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';

// Import torch plugin
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';


@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    LocationAccuracy,
    Geolocation,
    AndroidPermissions,
    { 
      provide: RouteReuseStrategy, 
      useClass: IonicRouteStrategy 
    }
  ],
  bootstrap: [AppComponent],
})

export class AppModule {}

Enable GPS in Ionic 6 App

To turn on mobile device GPS, you have to create a button on clicking it checkPermission function wil trigger, and display longitude, latitude, location accuracy, and time stamp.

Update home.page.html component file:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Turn on GPS in Ionic
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-button color="danger" (click)="checkPermission()">
    Enable GPS Locaction
  </ion-button>

  <ion-row>
    <ion-col>Longtitude</ion-col>
    <ion-col> {{locationCordinates.longitude}}</ion-col>
  </ion-row>
  <ion-row>
    <ion-col>Latitude</ion-col>
    <ion-col>{{locationCordinates.latitude}}</ion-col>
  </ion-row>
  <ion-row>
    <ion-col>Location accuracy</ion-col>
    <ion-col>{{locationCordinates.accuracy}}</ion-col>
  </ion-row>
  <ion-row>
    <ion-col>Timestamp</ion-col>
    <ion-col>{{locationCordinates.timestamp | date:'medium'}}</ion-col>
  </ion-row>  
</ion-content>

The checkPermission() method asks for location permission in android and enables the GPS; also, locationAccPermission helps enable the GPS else to throw an error. Likewise, enable GPS to look for latitude, longitude, accuracy, and timestamp.

Update home.page.ts component file:

import { Component } from '@angular/core';

import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';


@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  locationCordinates: any;
  timestamp: any;

  constructor(
    private locationAccuracy: LocationAccuracy,
    private geolocation: Geolocation,    
    private androidPermissions: AndroidPermissions
  ) {
    this.locationCordinates = {
      latitude: "",
      longitude: "",
      accuracy: "",
      timestamp: ""
    }
    this.timestamp = Date.now();
  }

  checkPermission() {
    this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION).then(
      result => {
        if (result.hasPermission) {
          this.enableGPS();
        } else {
          this.locationAccPermission();
        }
      },
      error => {
        alert(error);
      }
    );
  }

  locationAccPermission() {
    this.locationAccuracy.canRequest().then((canRequest: boolean) => {
      if (canRequest) {
      } else {
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
          .then(
            () => {
              this.enableGPS();
            },
            error => {
              alert(error)
            }
          );
      }
    });
  }

  enableGPS() {
    this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
      () => {
        this.currentLocPosition()
      },
      error => alert(JSON.stringify(error))
    );
  }

  currentLocPosition() {
    this.geolocation.getCurrentPosition().then((response) => {
      this.locationCordinates.latitude = response.coords.latitude;
      this.locationCordinates.longitude = response.coords.longitude;
      this.locationCordinates.accuracy = response.coords.accuracy;
      this.locationCordinates.timestamp = response.timestamp;
    }).catch((error) => {
      alert('Error: ' + error);
    });
  }

}

Test Ionic GPS App

In the last eventual step, you have to run the following commands to test the application:

# iOS
ionic cordova platform add ios

# Android
ionic cordova platform add android

# Windows
ionic cordova platform add windows

In the next step create the build in ionic:

# iOS
ionic cordova build ios

# Android
ionic cordova build android

# Windows
ionic cordova build windows

Lastly, you can run app to test the feature:

# iOS
ionic cordova run ios -l

# Android
ionic cordova run android -l

# Windows
ionic cordova run windows -l

Conclusion

Throughout this Ionic GPS example, you have learned how to enable GPS in Ionic app without moving away from the current application.