How to Find Nearest Location using Geolocation API in React 18

Last Updated on by in React JS

In this tutorial, we will teach you how to find and show the current or nearest location using latitude and longitude in React js application.

We will install and use the react-geocode library as well as the Geolocation JavaScript API to get the current user geolocation in React.

The geolocation API is a browser-based API that allows web developers to obtain the location information of a user’s device.

It might be a smartphone or a computer using various sensors, including GPS, Wi-Fi, and cellular networks.

The API is commonly used in web applications to provide location-aware functionality, such as finding nearby restaurants, mapping directions, or displaying weather information.

To use the geolocation API, the user must first permit the web application to access their location data.

Once permission is granted, the API retrieves the location data.

It returns it to the application as latitude and longitude coordinates, along with other information such as accuracy, altitude, and speed.

Most modern web browsers, including Chrome, Firefox, Safari, and Microsoft Edge, support the geolocation API.

React Find Nearest Location using Latitude and Longitude Example

  • Step 1: Download React Framework
  • Step 2: Install React Geocode Package
  • Step 3: Build Functional Component
  • Step 4: Get Nearest Location in React
  • Step 9: Register New Component
  • Step 10: Start React Server

Download React Framework

The first begins with downloading a fresh React framework; you have to build a new React project using create-react-app.

npx create-react-app react-demo

Navigate to the project folder:

cd react-demo

Install React Geocode Package

In this step, you will execute the suggested command and install the react geocode library.

npm install react-geocode --legacy-peer-deps

Build Functional Component

Inside the src/ folder, you will have to create the features/ folder, and then define the LocationComp component by adding the given code into the LocationComp.js file.

import React from 'react'

function LocationComp() {
  return (
    <div></div>
  )
}

export default LocationComp

Get Nearest Location in React

In the previous step, we created a brand new component to retrieve the location data; navigate to the features/LocationComp.js file and add all the given code into the file.

import React, { useEffect, useState } from "react";

import Geocode from "react-geocode";

// set Google Maps Geocoding API for purposes of quota management. Its optional but recommended.
Geocode.setApiKey("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

function LocationComp() {
  const [placename, setPlaceName] = useState(null);
  const [error, setError] = useState("");

  const geolocationAPI = navigator.geolocation;

  useEffect(() => {
    if (!geolocationAPI) {
      setError("Geolocation API is not available in your browser!");
    } else {
      Geocode.fromLatLng("48.8583701", "2.2922926").then(
        (response) => {
          const address = response.results[0].formatted_address;
          let city;
          for (let i = 0; i < response.results[0].address_components.length; i++) {
            for (let j = 0; j < response.results[0].address_components[i].types.length; j++) {
              switch (response.results[0].address_components[i].types[j]) {
                case "locality":
                  city = response.results[0].address_components[i].long_name;
                  break;
              }
            }
          }
          setPlaceName(city);
        },
        (error) => {
          console.error(error);
        }
      );
      
    }
  }, []);

  return (
    <>
      <h4>Your coordinates are: {placename}</h4>
    </>
  );
}

export default LocationComp;

Register New Component

In React, the App.js file is ideally the major entry point for our application.

It is where we are going to register the location component.

You can add the following code to the src/App.js file.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import LocationComp from "./features/LocationComp";

function App() {
  return (
    <div className="container mt-3">
      <h2 className="mb-3">React Show Current User Location Example</h2>
      <LocationComp />
    </div>
  );
}

export default App;

Start React Server

To start the development server, navigate to your React project folder.

Execute the given command and open the app with the given url.

npm start
http://localhost:3000

How to Find Nearest Location using GeoLocation API in React

Conclusion

In this step-by-stop post, we have managed to demystify how to find the current and nearest location using latitude and longitude in React js application.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.