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.

npxshadcn@latest addhttps://rigidui.com/registry/use-location

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.

Live Preview

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

PropTypeDefaultDescription
apiUrlstring'https://nominatim.openstreetmap.org'The API endpoint URL for reverse geocoding requests
geolocationOptionsPositionOptions{ timeout: 10000, enableHighAccuracy: true }Configuration options for the browser geolocation API

Return Values

The hook returns an object containing location data and control functions:

PropertyTypeDescription
locationstringThe current location name (city, county, or state)
coordinatesLocationCoordinates | nullThe latitude and longitude coordinates of the current location
isLoadingbooleanLoading state indicator for location operations
errorstring | nullError message if location detection fails
getCurrentLocation() => voidFunction 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() => voidFunction to clear the current location and reset state