Ionic 5 Complete guide on Geolocation, permissions and auto-turn on GPS

Abhijeet Rathore
Enappd
Published in
12 min readJul 25, 2020
Ionic 5 Geolocation in React Capacitor

In this blog post you will learn how to implement Geolocation in each of the following Ionic 5 variations

Part 1 — Ionic 5 with React and Capacitor ✅

Part 2— Ionic 5 with Angular and Cordova (Pending)

Part 3— Ionic 5 with Angular and Capacitor ✅

Along with these features, we’ll also check the functionality of

  • Requesting location permission in Ionic, and
  • Auto turn-on GPS from inside your app 😍

This blogpost is part of a new blog series — Ionic 5 Complete Guides, to cover One Single Feature in All Ionic Variations in one blog. Since Ionic has now expanded to cover frameworks like Angular, React, Vue, Cordova and Capacitor, it is high time to have a single place to learn about a feature — in all its different forms.

Different forms of Ionic — Intro

What is Ionic

You probably already know about Ionic, but I’m putting it here just for the sake of beginners.

To be concise — If you create Native apps in Android, you code in Java/Kotlin. If you create Native apps in iOS, you code in Obj-C/Swift. Both of these are powerful but complex languages. With Ionic you can write a single piece of code for your app that can run on both iOS and Android (and browser!), that too with the simplicity of HTML, CSS, and JS.

Forms of Ionic

Ionic has made itself language agnostic to some extent, integrating some of the most popular JS frameworks. At present, Ionic apps can be written with

  • AngularJS as front-end
  • ReactJS as front-end
  • VanillaJS as front-end
  • VueJS as front-end
  • Cordova as build environment
  • Capacitor as build environment

As you can see, Ionic can be adopted by a large community of developers, and hence there are always confusion about which plugin to use in which framework. That’s the whole purpose of this series of Complete Guide posts.

Which Framework is best in Ionic?

That is a highly debatable topic. All front-end frameworks have their pros and cons. Effectively you can make a fully working app in any of these frameworks, just the ease and way of coding is different in each one. At Enappd, we have tried our hands with Angular and React in Ionic, and we can’t say for sure which one is faster/better. While Angular feels better in handling data for bigger apps, React feels a bit faster. 🤷‍♂

Cordova vs Capacitor

  • Cordova is a veteran, being around for 10+ years. Capacitor is a new entry from Ionic team itself, and has a fresh approach to the native build process
  • While Cordova’s community is older, bigger (wiser?), Capacitor is quickly gaining traction
  • Cordova has more plugins than Capacitor, and hence many a times, you end up using Cordova plugins in Capacitor environment as well
  • Cordova has ease of native builds right from the CLI, while Capacitor requires you to use native IDEs (XCode, Android Studio) to build apps
  • Cordova builds the native environment each time, while Capacitor keeps it as a source asset. So only changes are copied at build time. You can also include extra native code in the platforms built by Capacitor

What is Geolocation? 🗺

The most famous and familiar location feature — Geolocation, is the ability to track a device’s whereabouts using GPS, cell phone towers, WiFi access points or a combination of these. Both mobile and desktop devices can use geolocation. There are apps which use location once, and there are apps which continuously track your location as well (😱)

There are some famous Location-Based Apps.

Five Geolocation Apps you may have come across

  • Uber / Lyft — Cab booking (one time and continuous tracking)
  • Google Maps (of course) — Map services
  • Swiggy / Zomato/ Uber Eats — Food delivery
  • Fitbit — Fitness app
  • Instagram / Facebook — For tagging photos

Post Structure

The post structure will remain mostly common for all frameworks

  1. Create a simple Ionic 5 app with required framework. Create Basic UI to test the feature

2. Install and import required plugins

3. Implement Google Map

4. Implement GPS permissions

5. Implement auto turn-on GPS

6. Implement geolocation and display user position on Google Map

7. Build on device and test (Android / iOS)

PART 1 — Ionic 5 in React and Capacitor

Build Environment

Node 12.14.1 (any 12.x version should work)
Ionic 5 (CLI 5.3.0)
Capacitor 2.0
React 16.13.x

STEP 1.1 — Create a simple Ionic React app with Capacitor

Make sure you have the latest Ionic CLI. This will ensure you are using everything latest. Ensure latest Ionic CLI installation using

$ npm install -g ionic@latest

Creating a basic Ionic-React app (check all options). Start a basic blank starter using

$ ionic start IonicGeo blank --type=react --capacitor
  • --capacitor tells the CLI to create a Capacitor integration, not Cordova!!
  • --type=react tells the CLI to create an Ionic React app
  • blank template gives a blank home page

Run the app in browser using (yes you guessed it right)

$ ionic serve

You’ll see an empty page open up. That’s fine, your app is running correctly

STEP 1.2 — Add Google Map and other required plugins

We need to add following plugins/packages

  • Google Maps package
  • Location Permission plugin
  • GPS auto-turn on plugin
  • Geolocation plugin
  1. Add Google Map package
$ npm install --save google-map-react$ npm i --save @types/google-map-react

2. Geolocation Permission plugin

This plugin is only required for Android

// Install Core library (once per project)
$ npm install @ionic-native/core
$ npm install cordova-plugin-android-permissions$ npm install @ionic-native/android-permissions

3. Auto turn-on GPS plugin

This Cordova/Phonegap plugin for Android and iOS to request enabling/changing of Location Services by triggering a native dialog from within the app, avoiding the need for the user to leave your app to change location settings manually.

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

4. Geolocation plugin

Capacitor has in-built Geolocation plugin, so you don’t have to include another plugin in it. It can be directly accessed by importing in any file like this

import { Plugins} from "@capacitor/core";const { Geolocation} = Plugins;

Alrighty, we’re all set with plugins. Now we import the plugins in our homepage, and add functionalities.

STEP 1.3 — Implement Google Map

So I have arranged my files in a standard fashion

  • HomeView.tsx — contains the view
  • HomeContainer.tsx — contains the logic of the view
  • Location.tsx — contains the common functions of geolocation, permission etc.
  • styles.css — styles for the page

The App.tsx points to HomeContainer.tsx on first load, and it has HomeView.tsx as a child view.

My HomeView.tsx contains following code for Google Map

where center is an object with coordinates

center: {
lat: 12.934485599999999
lng: 77.6192336
}

Note: Enter your own Google maps API key in the component to view map correctly.

With proper styling (width:100%, height: 100%), you should see the Google Map like following

Notice that the marker is in the center of the map. This way you can just supply one coordinate for both center and marker location.

STEP 1.4 — Implement GPS permissions

This plugin serves to check whether the app has the permission to access location, if not, it requests permission from the user for the same.

I keep these functions in Location.tsx so I can use it in any of the pages

You can call these functions in yourHomeContainer.tsx right after it loads, or when the user actually requests the location. This really depends on the UX of your app.

If checkGPSPermission returns true , or requestGPSPermission returns GOT_PERMISSION , you can proceed to check if the device GPS is ON or OFF (only for Android )

STEP 1.5— Implement auto turn-on GPS

In your Location.tsx , add the function for checking and then turning on GPS

If the functions resolves to true , you can proceed to get Geolocation in the app, using the next step

STEP 1.6— Implement geolocation and display user position on Google Map

You can request geolocation in either HomeContainer.tsx orLocation.tsx, depending on whether you are updating your state variables directly or not.

Important: The Geolocation plugin in Capacitor will give you two methods

  • getCurrentPosition
  • watchPosition

Intuitively, everyone tries to use the getCurrentPosition method. But interestingly this method returns you the last known device location requested in your device’s Google Maps app. While Capacitor developers say this is the way it is supposed to be, it feels counter-intuitive.

Solution : You can use watchPosition method to get your current location (continuously). But to reduce battery usage, as soon as you get the first location data, you can call clearWatch method to stop watching location. You can even keep watching the location for few seconds just to make sure you have consistent reading !

Now, combining all the above functionalities, we get following code in our four files

HomeView.tsx

HomeContainer.tsx

Location.tsx

styles.css

Lets build the app on a device and test it out real quick.

STEP 1.7 — Build on device and test (Android / iOS)

Before building the app on device, compile the web assets using

$ ionic build

Add android platform using

$ npx cap add android

Once Android is added, open Android Studio using

$ npx cap open android

Build the app from Android Studio to your Android device. Here’s how the functionality works for my device (OnePlus 6T, Android X)

1. When app doesn’t have permission AND GPS is OFF

Ionic React Capacitor — Get location permission and turn on GPS
Ionic React Capacitor — Get location permission and turn on GPS

2. When app has permission AND GPS is OFF

Ionic React Capacitor — Turn on GPS
Ionic React Capacitor — Turn on GPS

3. When app doesn’t have permission AND GPS is ON

Ionic React Capacitor — Get location permission
Ionic React Capacitor — Get location permission

That’s it, you just implemented geolocation in your Ionic React Capacitor app, including asking for permission and automatically turning on GPS.

PART 2— Ionic 5 in Angular and Capacitor

Build Environment

Node 12.14.1 (any 12.x version should work)
Ionic 5 (CLI 5.3.0)
Capacitor 2.0
Angular ~9.1.x

STEP 2.1 — Create a simple Ionic Angular app with Capacitor

Make sure you have the latest Ionic CLI. This will ensure you are using everything latest. Ensure latest Ionic CLI installation using

$ npm install -g ionic@latest

Creating a basic Ionic-Angular app (check all options). Start a basic blank starter using

$ ionic start IonicGeo blank --type=angular --capacitor
  • --cordova tells the CLI to create a Capacitor integration, not Cordova!!
  • --type=angular tells the CLI to create an Ionic Angular app
  • blank template gives a blank home page

Run the app in browser using

$ ionic serve

You’ll see an empty page open up. That’s fine, your app is running correctly

STEP 2.2 — Add Google Map and other required plugins

We need to add following plugins/packages

  • Google Maps package
  • Location Permission plugin
  • GPS auto-turn on plugin
  • Geolocation plugin
  1. Add Google Map package
$ npm install @agm/core

2. Geolocation Permission plugin

This plugin is only required for Android

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

3. Auto turn-on GPS plugin

This Cordova/Phonegap plugin for Android and iOS to request enabling/changing of Location Services by triggering a native dialog from within the app, avoiding the need for the user to leave your app to change location settings manually.

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

4. Geolocation plugin

As mentioned earlier in React section, Capacitor has in-built Geolocation plugin, so you don’t have to include another plugin in it. It can be directly accessed by importing in any file like this

import { Plugins} from "@capacitor/core";const { Geolocation} = Plugins;

Now let’s import the plugins in our homepage, and add functionalities.

STEP 2.3 — Implement Google Map

Ionic Angular apps have a standard module arrangement of files. Each page is contained in a folder with a

  • .scss — styling
  • .module.ts — for imports, declaration etc., and
  • .page.ts — main controller file
  • .html — view file

In our sample app, we’ll have a default home page folder with these files. Let’s add a Google map using agm in the home page.

First, import AgmCoreModule in app.module.ts like following

import { AgmCoreModule } from '@agm/core';
......
@NgModule({
...
imports: [
....
AgmCoreModule.forRoot({
apiKey: 'YOUR_GOOGLE_MAPS_API_KEY',
}),
],
....
})

Note: Enter your own Google maps API key to view map correctly.

Again, import AgmCoreModule in your home.module.ts as

import { AgmCoreModule } from '@agm/core';...
@NgModule({
imports: [
.....
AgmCoreModule,
.....
],
})

My home.page.html contains following code for Google Map

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="15" [disableDefaultUI]="false">
<agm-marker [latitude]="lat" [longitude]="lng" [markerDraggable]=true></agm-marker>
</agm-map>

where lat and lng are arbitrary coordinate defined in home.page.ts . This will show a familiar home page with Google map, with a centered marker

Google Map implementation in Ionic Angular Capacitor app
Google Map implementation in Ionic Angular Capacitor app

STEP 2.4 — Implement GPS permissions

I’ll keep the common functions in a service app/location.service.ts

You can call these functions in yourhome.page.ts right after it loads, or when the user actually requests the location. This really depends on the UX of your app.

If checkGPSPermission returns true , or requestGPSPermission returns GOT_PERMISSION , you can proceed to check if the device GPS is ON or OFF (only for Android )

STEP 2.5 — Implement auto turn-on GPS

In your location.service.ts , add the function for checking and then turning on GPS

If the functions resolves to true , you can proceed to get Geolocation in the app, using the next step

STEP 2.6 — Implement geolocation and display user position on Google Map

You can request geolocation in either home.page.ts orlocation.service.ts, depending on whether you are updating your variables in controller or not.

Note: Check Section 1.6 for why we are using watchPosition and not getCurrentPosition

You can use watchPosition method to get your current location (continuously). But to reduce battery usage, as soon as you get the first location data, you can call clearWatch method to stop watching location. You can even keep watching the location for few seconds just to make sure you have consistent reading !

Now, combining all the above functionalities, we get following code in our files

home.page.html

home.page.ts

location.service.ts

home.page.scss

STEP 2.7 — Build on device and test (Android)

Before building the app on device, compile the web assets using

$ ionic build

Add android platform using

$ npx cap add android

Once Android is added, open Android Studio using

$ npx cap open android

Build the app from Android Studio to your Android device. Here’s the app running on my device (OnePlus 6T, Android X)

(When app doesn’t have location permission and GPS is OFF. Other scenarios are shown in Ionic React Section 1.7)

Ionic Angular Capacitor — Get location permission and turn on GPS
Ionic Angular Capacitor — Get location permission and turn on GPS

This is how you implement Geolocation in Ionic Angular Capacitor app, including asking for permission and automatically turning on GPS.

More to come

I will soon publish the final part of this blog i.e. Geolocation in

  • Ionic 5 with Angular and Cordova

Ionic React Full App

If you need a base to start your next Ionic 5 React Capacitor app, you can make your next awesome app using Ionic 5 React Full App in Capacitor

Ionic 5 React Full App in Capacitor from Enappd
Ionic 5 React Full App in Capacitor from Enappd

Ionic Capacitor Full App (Angular)

If you need a base to start your next Angular Capacitor app, you can make your next awesome app using Capacitor Full App

Capacitor Full App with huge number of layouts and features
Capacitor Full App with huge number of layouts and features

Next Steps

Now that you have learned how to implement Geolocation in your Ionic 5 app, you can also try the following blogs.

--

--

Abhijeet Rathore
Enappd
Editor for

Rocket scientist turned programmer. Co-founder at Enappd and Youstart Education. Trying to make the world a better place, one solution at a time.