useGeolocation
Access and track the user's geographic location with real-time updates, high accuracy support, and comprehensive error handling. Perfect for maps, location-based services, and navigation applications.
Interactive Demo
Latitude
Loading...
Longitude
Loading...
Accuracy
Loading...
Implementation
interface GeolocationState {
latitude: number | null;
longitude: number | null;
accuracy: number | null;
error: string | null;
loading: boolean;
}
export function useGeolocation(options?: PositionOptions) {
const [state, setState] = useState<GeolocationState>({
latitude: null,
longitude: null,
accuracy: null,
error: null,
loading: true,
});
useEffect(() => {
if (!navigator.geolocation) {
setState((prev) => ({
...prev,
error: "Geolocation is not supported by your browser",
loading: false,
}));
return;
}
const successHandler = (position: GeolocationPosition) => {
setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
error: null,
loading: false,
});
};
const errorHandler = (error: GeolocationPositionError) => {
setState((prev) => ({
...prev,
error: error.message,
loading: false,
}));
};
navigator.geolocation.getCurrentPosition(successHandler, errorHandler, options);
const watchId = navigator.geolocation.watchPosition(successHandler, errorHandler, options);
return () => navigator.geolocation.clearWatch(watchId);
}, [options]);
return state;
}
Usage Examples
import { useGeolocation } from '@/components/hooks/useGeolocation';
function LocationTracker() {
const { latitude, longitude, accuracy, error, loading } = useGeolocation({
enableHighAccuracy: true,
maximumAge: 0,
timeout: 5000,
});
if (loading) return <div>Loading location...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<div>Latitude: {latitude}</div>
<div>Longitude: {longitude}</div>
<div>Accuracy: ±{accuracy}m</div>
</div>
);
}
Documentation
Key Features
- Real-time location tracking
- High accuracy support
- Error handling and loading states
- TypeScript support
- Automatic cleanup of watchers
- Configurable options
Common Use Cases
- Maps and navigation
- Location-based services
- Weather applications
- Fitness tracking
- Geofencing applications
API Reference
useGeolocation(options?: PositionOptions)
Returns the current geolocation state and updates in real-time.
Parameters:
- enableHighAccuracy: Boolean to request better accuracy
- maximumAge: Maximum cached position age in milliseconds
- timeout: Maximum time to wait for reading in milliseconds
Returns:
- latitude: Current latitude or null
- longitude: Current longitude or null
- accuracy: Position accuracy in meters or null
- error: Error message or null
- loading: Boolean indicating loading state
Security Considerations
The Geolocation API is only available in secure contexts (HTTPS). Users must explicitly grant permission to access their location. The permission can be managed through browser settings.
Browser Compatibility
The Geolocation API is widely supported across modern browsers. However, availability may be limited in some regions or when using certain privacy features. Always implement appropriate fallbacks.