Geolocation refers to the process of identifying the location of a user’s device, typically a computer or mobile device, and using that information to provide location-based services or content. This is done by using the Geolocation API.
Usage
The Geolocation API includes the function useGeolocation(), which returns an object with two properties:
coords: An object containing the current geolocation coordinates (latitude and longitude).error: An error object if the geolocation request fails.
Read more about the Geolocation API here:
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
Let’s build an example which displays the user’s current coordinates. We will make a hook in React to access a user’s geolocation with permission, then display the results in the browser using a custom component called Geolocation.
Procedure
Let’s make a React hook which fetches the geolocation data and provides error handling:
src/hooks/useGeolocation.js
import { useState } from "react";
export const useGeolocation = () => {
const [coords, setCoords] = useState(null);
const [error, setError] = useState(null);
const { geolocation } = navigator;
if (!error && !coords) {
geolocation.getCurrentPosition(
(res) => {
setCoords(res.coords);
}, (res) => {
setError(res.message);
});
}
return { error, coords };
};
Next, we’ll make a component which uses the hook and displays the current latitude and longitude of the user:
src/components/geolocation/Geolocation.tsx
import "./Geolocation.css";
import { useGeolocation } from "../../hooks/useGeolocation";
interface Geo {
coords: GeolocationCoordinates | null;
error: any;
}
function Geolocation() {
const loc = useGeolocation() as Geo;
return (
<div>
<h1>Your Location:</h1>
{loc?.coords ? (
<>
<div>
<b>Lat:</b> {loc.coords.latitude}
</div>
<div>
<b>Lon:</b> {loc.coords.longitude}
</div>
</>
) : (
"loading..."
)}
</div>
);
}
export default Geolocation;
So now if we go to the browser, this information will be displayed:

