Skip to main content

useGeoLocation

useGeoLocation is a custom hook to track the user's geolocation with retry functionality.

Usage

import { useGeoLocation } from "./useGeoLocation";

export default function GeoLocationExample() {
const { loading, error, coords } = useGeoLocation({ enableHighAccuracy: true });

if (loading) return <p>Fetching location...</p>;
if (error) return <p>Error: {error.message}</p>;

return (
<p>
Latitude: {coords?.latitude}, Longitude: {coords?.longitude}
</p>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
enableHighAccuracybooleanfalseRequests the most accurate location possible.
maximumAgenumber0Maximum age (in milliseconds) of a cached position before a fresh one is requested.
timeoutnumber10000Maximum time (in milliseconds) to wait for a position.
retryLimitnumber3Maximum number of retry attempts in case of failure.
retryDelaynumber2000Delay (in milliseconds) between retries.

Behavior

  • Fetches the user's geolocation using navigator.geolocation.watchPosition().
  • Automatically retries fetching the location if it fails, up to the retryLimit.
  • Returns the latest available coordinates.
  • Clears the geolocation watch when the component unmounts.

Return Value

useGeoLocation returns an object containing:

PropertyTypeDescription
loadingbooleantrue if location is being fetched, otherwise false.
error{ code: number; message: string } | nullContains error details if location retrieval fails.
coordsGeolocationCoordinates | nullThe latest coordinates (latitude, longitude, accuracy, etc.).