useGeolocation
useGeolocation
is a React hook that retrieves and tracks the user's geographical location. It uses the browser's Geolocation API
to support both one-time position retrieval and continuous location tracking.
Interface
function useGeolocation(options: GeolocationOptions): Object;
Parameters
- optionsGeolocationOptions
Geolocation options configuration
- options.mountBehaviorGeolocationMountBehaviorType
How the hook behaves on mount:
- If not provided, no automatic location fetching occurs
- 'get': automatically fetches location once when component mounts
- 'watch': automatically starts tracking location changes when component mounts - options.enableHighAccuracyboolean · false
If true, provides more accurate position information (increases battery consumption)
- options.maximumAgenumber · 0
Maximum age in milliseconds of a cached position that is acceptable to return
- options.timeoutnumber · Infinity
Maximum time (in milliseconds) allowed for the location request
- options.mountBehaviorGeolocationMountBehaviorType
Return Value
- Object
containing location data and related functions
- loadingboolean
Whether location data is currently being fetched.
- errorCustomGeoLocationError|null
Error object if an error occurred, or null The hook uses standard Geolocation API error codes (
1-3
) and adds a custom code (0
)
:0
- Geolocation is not supported by the environment
:1
- User denied permission to access geolocation
:2
- Position unavailable
:3
- Timeout - geolocation request took too long. - dataGeolocationData|null
Location data object or null
: latitudenumber
- The latitude in decimal degrees
: longitudenumber
- The longitude in decimal degrees
: accuracynumber
- The accuracy of position in meters
: altitudenumber|null
- The altitude in meters above the WGS84 ellipsoid
: altitudeAccuracynumber|null
- The altitude accuracy in meters
: headingnumber|null
- The heading in degrees clockwise from true north
: speednumber|null
- The speed in meters per second
: timestampnumber
- The time when the position was retrieved. - getCurrentPositionFunction
Function to get the current position once.
- startTrackingFunction
Function to start tracking location changes.
- stopTrackingFunction
Function to stop tracking location.
- isTrackingboolean
Whether location tracking is currently active.
- loadingboolean
Example
// Basic usage
const {
loading,
error,
data,
getCurrentPosition
} = useGeolocation();
// Automatically fetch location when component mounts
const {
loading,
error,
data
} = useGeolocation({ mountBehavior: 'get' });
// Location tracking
const {
loading,
error,
data,
startTracking,
stopTracking,
isTracking
} = useGeolocation();
const handleStartTracking = () => {
startTracking();
};
const handleStopTracking = () => {
stopTracking();
};