Skip to content
usefy

useGeolocation

Browser & device

A powerful React hook for accessing device geolocation with real-time tracking and distance calculation

Install

$ npm install @usefy/use-geolocation

Quick start

useGeolocation.tsx
import { useGeolocation } from "@usefy/use-geolocation";

function MyLocation() {
  const { position, loading, error } = useGeolocation();

  if (loading) return <p>Loading location...</p>;
  if (error) return <p>Error: {error.message}</p>;
  if (!position) return <p>No position yet</p>;

  return (
    <div>
      <p>Latitude: {position.coords.latitude}</p>
      <p>Longitude: {position.coords.longitude}</p>
      <p>Accuracy: {position.coords.accuracy}m</p>
    </div>
  );
}

API reference

useGeolocation(options?)

A hook that manages geolocation state with real-time tracking and utility functions.

Parameters

ParameterTypeDescription
optionsUseGeolocationOptionsOptional configuration object

Options

OptionTypeDefaultDescription
enableHighAccuracybooleanfalseEnable high accuracy mode (uses GPS, consumes more battery)
maximumAgenumber0Maximum age of cached position in milliseconds
timeoutnumber30000Timeout in milliseconds for position request
watchbooleanfalseStart watching position immediately on mount
immediatebooleantrueGet initial position immediately on mount
onSuccess(position: GeoPosition) => voidCallback when position is successfully retrieved
onError(error: GeolocationError) => voidCallback when an error occurs
onPositionChange(position: GeoPosition) => voidCallback when position changes (during watch mode)
onPermissionChange(state: PermissionState) => voidCallback when permission state changes

Returns UseGeolocationReturn

PropertyTypeDescription
positionGeoPosition | nullCurrent position data (null if not yet retrieved)
loadingbooleanLoading state (true while fetching position)
errorGeolocationError | nullError object (null if no error)
permissionPermissionStateCurrent permission state (prompt, granted, denied, unavailable)
isSupportedbooleanWhether geolocation is supported in this environment
getCurrentPosition() => voidManually get current position (one-time request)
watchPosition() => voidStart watching position for real-time updates
clearWatch() => voidStop watching position
distanceFrom(lat: number, lon: number) => number | nullCalculate distance from current position to target coordinates in meters
bearingTo(lat: number, lon: number) => number | nullCalculate bearing/direction from current position to target coordinates (0-360 degrees)

Error Codes

CodeDescription
PERMISSION_DENIEDUser denied geolocation permission
POSITION_UNAVAILABLEPosition information unavailable
TIMEOUTPosition request timed out
NOT_SUPPORTEDGeolocation is not supported in this environment

Go deeper

This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.

More in browser & device