Ionic 5 and React: Geolocation

paulhalliday

Paul Halliday

Posted on April 27, 2020

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.

Video

Want to see the video for this article? Check it out below:

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;

We can then add this into Home.tsx like so:

import {
  IonContent,
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar,
  IonGrid,
  IonCol,
  IonRow,
} from "@ionic/react";
import React from "react";
import ExploreContainer from "../components/ExploreContainer";
import "./Home.css";
import GeolocationButton from "../components/GeolocationButton";

const Home: React.FC = () => {
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Geolocation</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent>
        <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Geolocation</IonTitle>
          </IonToolbar>
        </IonHeader>

        <div className="container">
          <GeolocationButton />
        </div>
      </IonContent>
    </IonPage>
  );
};

export default Home;

I've added the container class to our button to center it in the middle of IonContent:

.container {
  text-align: center;
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

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

Ionic 5 and React: Geolocation
San Fransisco!

💖 💪 🙅 🚩
paulhalliday
Paul Halliday

Posted on April 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related