arrow-left arrow-right brightness-2 chevron-left chevron-right facebook-box facebook loader magnify menu-down rss-box star twitter-box twitter white-balance-sunny window-close
Ionic 5 and React: Geolocation
2 min read

Ionic 5 and React: Geolocation

Ionic 5 and React: Geolocation

In this article we'll be looking at how to get the user's current location using the Geolocation plugin alongside our Ionic and React application(s). With this plugin we'll be able to get the user's latitude, longitude , altitude, and so on.

New Ionic React project

In order to ensure we're all starting from the same point, run the following inside of your terminal:

$ ionic start ionic_geolocation

? Framework:
> React

? Starter template:
> blank

? Integrate Capacitor
> Y

$ cd ionic_geolocation

$ npm install @ionic-native/core
$ npm install cordova-plugin-geolocation
$ npm install @ionic-native/geolocation

$ ionic cap sync

$ code .

$ ionic serve

This may look like a lot, but here we're essentially:

  • Creating a new Ionic and React project
  • Adding the Geolocation plugin
  • Update web/native capacitor elements
  • Running a development server at http://localhost:8100

Location

We'll then create ourselves a new GeolocationButton component which can be used to interact with the Geolocation plugin.

This will either display an IonLoading component whilst the Geolocation.getCurrentPosition is being called, show an IonToast with an error message (usually if the user has blocked permissions), or show the current latitude and longitude as the button text:


import { Geolocation, Geoposition } from '@ionic-native/geolocation';
import { IonButton, IonLoading, IonToast } from '@ionic/react';
import React, { useState } from 'react';

interface LocationError {
    showError: boolean;
    message?: string;
}

const GeolocationButton: React.FC = () => {
    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<LocationError>({ showError: false });
    const [position, setPosition] = useState<Geoposition>();

    const getLocation = async () => {
        setLoading(true);

        try {
            const position = await Geolocation.getCurrentPosition();
            setPosition(position);
            setLoading(false);
            setError({ showError: false });
        } catch (e) {
            setError({ showError: true, message: e.message });
            setLoading(false);
        }
    }

    return (
        <>
            <IonLoading
                isOpen={loading}
                onDidDismiss={() => setLoading(false)}
                message={'Getting Location...'}
            />
            <IonToast
                isOpen={error.showError}
                onDidDismiss={() => setError({ message: "", showError: false })}
                message={error.message}
                duration={3000}
            />
            <IonButton color="primary" onClick={getLocation}>{position ? `${position.coords.latitude} ${position.coords.longitude}` : "Get Location"}</IonButton>
        </>
    );
};

export default GeolocationButton;

If all goes well, clicking on the button will give us the current latitude and longitude as we expect:

San Fransisco!