useLocation
A React hook for location detection and reverse geocoding that provides easy access to user's current location with browser geolocation API.
Installation
Install the useLocation component using your preferred package manager.
Usage
The useLocation hook provides a simple interface for getting user location through browser geolocation API and converting coordinates to readable location names. It handles loading states, errors, and provides both automatic and manual location detection.
Discover Its Features
The useLocation component is packed with powerful features designed to provide an exceptional user experience.
Browser Geolocation
Leverages the browser's native geolocation API to detect user's current position with high accuracy.
Reverse Geocoding
Converts latitude/longitude coordinates into human-readable location names using OpenStreetMap's Nominatim API.
Configurable Options
Customizable API endpoints and geolocation settings including timeout, accuracy, and cache options.
Error Handling
Comprehensive error handling for permission denials, timeouts, and network failures with descriptive messages.
API Reference
Prop | Type | Default | Description |
---|---|---|---|
apiUrl | string | 'https://nominatim.openstreetmap.org' | The API endpoint URL for reverse geocoding requests |
geolocationOptions | PositionOptions | { timeout: 10000, enableHighAccuracy: true } | Configuration options for the browser geolocation API |
Return Values
The hook returns an object containing location data and control functions:
Property | Type | Description |
---|---|---|
location | string | The current location name (city, county, or state) |
coordinates | LocationCoordinates | null | The latitude and longitude coordinates of the current location |
isLoading | boolean | Loading state indicator for location operations |
error | string | null | Error message if location detection fails |
getCurrentLocation | () => void | Function to get the user's current location using browser geolocation |
getLocationFromCoordinates | (lat: number, lon: number) => Promise<void> | Function to get location name from specific coordinates |
clearLocation | () => void | Function to clear the current location and reset state |