useGeolocation
Declarative hook for the browser Geolocation API.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
options | PositionOptions | {} | Options for getCurrentPosition and watchPosition |
Data
Property | Type | Description |
---|---|---|
position | GeolocationPosition | null | The last known position from the Geolocation API |
error | GeolocationPositionError | null | The last encountered error, if any |
isLoading | boolean | Whether the hook is currently loading data |
clearWatch | () => void | Function to stop watching position changes |
Key Features & Details
- Declarative interface for both
getCurrentPosition
and continuouswatchPosition
. - Automatic cleanup on component unmount.
- Graceful fallback if Geolocation API is not supported.
- Fully typed with TypeScript.
Browser Support
- Chrome: Supported (since v5)
- Firefox: Supported (since v3.5)
- Safari: Supported (since 5)
- Edge: Supported
- Opera: Supported
Security Considerations
- Requires secure context (HTTPS).
- User permission prompt is shown on first request.
Best Practices & Caveats
- Always handle the
error
case to inform the user. - Clear the watch when no longer needed to save battery.
- Consider asking permission only when necessary.
- For frequent updates, throttle or debounce updates to avoid performance issues.
- Use
maximumAge
andtimeout
options wisely.
Examples
Basic Usage
const { position, error, isLoading } = useGeolocation();
if (error) {
console.error(error);
} else if (isLoading) {
console.log('Loading position...');
} else if (position) {
console.log(`Latitude: ${position.coords.latitude}`);
}
Full Example
import React from 'react';
import { useGeolocation } from '@/registry/hooks/use-geolocation';
export default function LocationDisplay() {
const { position, error, isLoading, clearWatch } = useGeolocation({
enableHighAccuracy: true,
maximumAge: 10000,
timeout: 5000,
});
if (error) return <p>Error: {error.message}</p>;
if (isLoading) return <p>Loading…</p>;
return (
<div>
<p>Lat: {position.coords.latitude}</p>
<p>Lon: {position.coords.longitude}</p>
<button onClick={clearWatch}>Stop Watching</button>
</div>
);
}