Getting Location Data with Ionic 4 and Capacitor

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Below you’ll find a quick demo on how to get GPS coordinates in your Ionic 4 project using Capacitor.

If you have not heard of Capacitor, it’s the replacement for Cordova from the Ionic team. It focuses on providing native functionality and plugins for Progressive Web Apps (PWAs), iOS and Android. It’s the future of hybrid mobile development.


Start by creating your Ionic project using the CLI:

$ ionic start coordinates tabs --type=angular --capacitor

$ cd coordinates

Setup Capacitor

Next, add Capacitor to our newly created Ionic project and include the app name and app id (ex: com.example.app). We’ll use npx to accomplish that task:

$ npx cap init coordinates com.example.app

Run Ionic build to get the www folder created:

$ ionic build

You can add your platforms with:

$ npx cap add ios
$ npx cap add android

Now, run ionic serve to build the app in your browser:

$ ionic serve

You should see the default ionic tabs dummy data. Open your project in your preferred text editor.

Open tab1.page.html, delete everything inside the ion-content tags and replace it with the markup below:

    <ion-item>Latitude: {{ latitude }}</ion-item>
    <ion-item>Longitude: {{ longitude }}</ion-item>

Above is just a quick Ionic card that prints out the coordinates. In your app, you probably want to plug these coordinates into another plugin or service, such as Google maps, weather, etc…

In the tab1.page.ts file, import the geolocation plugin from @capcitor/core:

import { Geolocation} from '@capacitor/core';

Create a variable for longitude and latitude with a type of number:

latitude: number;
longitude: number;

In the constructor, call our soon to be created function this.getLocataion():

constructor() {

Now lets create that async getLocation function and call the getCurrentPosition promise on the Geolocation class we imported:

async getLocation() {
  const position = await Geolocation.getCurrentPosition();
  this.latitude = position.coords.latitude;
  this.longitude = position.coords.longitude;

In the code, we assign the latitude and longitude to our previously created variables. Your screen should look like this:

coordinates app

And that’s it! Simple enough! Head over to the official docs to learn more about other methods available on the Geolocation API like watchPosition and addListener as well as specific permission notes for usage with iOS and Android.

Creative Commons License