useGeolocation
A custom hook that retrieves the user's current location using the browser's Geolocation API.
You can fetch the location once (get) or track it in real time (watch).
Codeโ
Interfaceโ
typescript
interface UseGeolocationOptions extends PositionOptions {
mountBehavior?: 'watch' | 'get';
}
interface UseGeolocationReturn {
data: GeolocationData | null;
error: GeolocationPositionError | Error | null;
loading: boolean;
isWatching: boolean;
get: () => void;
watch: () => void;
stopWatch: () => void;
}
type GeolocationData = GeolocationPosition['coords'] & { timestamp: number };
function useGeolocation(options?: UseGeolocationOptions): UseGeolocationReturn;
Optionsโ
| Name | Type | Default | Description |
|---|---|---|---|
enableHighAccuracy | boolean | false | Whether to request high-accuracy location (uses GPS, increases battery usage) |
timeout | number | Infinity | Maximum time allowed to obtain location information (milliseconds) |
maximumAge | number | 0 | Maximum age of cached location information (milliseconds) |
mountBehavior | 'watch' | 'get' | 'get' | How to fetch location when the hook mounts |
Returnsโ
| Name | Type | Description |
|---|---|---|
data | GeolocationData | null | Location data (latitude, longitude, accuracy, altitude, timestamp, etc.) |
error | GeolocationPositionError | Error | null | Error information |
loading | boolean | Whether location information is being fetched |
isWatching | boolean | Whether real-time location tracking is active |
get | () => void | Function to fetch the current location once |
watch | () => void | Function to start real-time location tracking |
stopWatch | () => void | Function to stop real-time location tracking |
GeolocationDataโ
| Name | Type | Description |
|---|---|---|
latitude | number | Latitude |
longitude | number | Longitude |
accuracy | number | Location accuracy (meters) |
altitude | number | null | Altitude (meters) |
altitudeAccuracy | number | null | Altitude accuracy (meters) |
heading | number | null | Direction of movement (0ยฐโ360ยฐ, north-based) |
speed | number | null | Movement speed (m/s) |
timestamp | number | Time when location was acquired |
Remarksโ
Caution
- HTTPS required: The Geolocation API only works in
HTTPSenvironments for security reasons. (localhostis an exception) - User permission required: Before accessing location information, the browser shows a permission prompt to the user. If denied, an error is returned.
- SSR environment: In server-side rendering environments,
navigator.geolocationdoes not exist; the hook detects this and returns an error. - Battery usage: Using
enableHighAccuracy: trueprovides more accurate location via GPS but increases battery consumption. - Watch mode: When using real-time tracking (
watch) mode, tracking is automatically stopped when the component unmounts.
Error Handling
Common errors from the Geolocation API:
PERMISSION_DENIED(code: 1): User denied location accessPOSITION_UNAVAILABLE(code: 2): Location information is unavailableTIMEOUT(code: 3): Location information could not be obtained within the specified time
Usageโ
Basic Usage (Fetch Location Once)โ
typescript
import { useGeolocation } from '@modern-kit/react';
const LocationComponent = () => {
const { data, error, loading } = useGeolocation();
if (loading) return <div>Fetching location...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!data) return null;
return (
<div>
<p>Latitude: {data.latitude}</p>
<p>Longitude: {data.longitude}</p>
<p>Accuracy: {data.accuracy}m</p>
</div>
);
};
Real-Time Location Trackingโ
typescript
import { useGeolocation } from '@modern-kit/react';
const RealTimeLocation = () => {
const { data, isWatching, watch, stopWatch } = useGeolocation({
mountBehavior: 'watch',
enableHighAccuracy: true
});
return (
<div>
<p>Tracking status: {isWatching ? 'Tracking' : 'Stopped'}</p>
{data && (
<>
<p>Latitude: {data.latitude}</p>
<p>Longitude: {data.longitude}</p>
</>
)}
<button onClick={isWatching ? stopWatch : watch}>
{isWatching ? 'Stop Tracking' : 'Start Tracking'}
</button>
</div>
);
};
Manually Fetching Locationโ
typescript
import { useGeolocation } from '@modern-kit/react';
const ManualLocation = () => {
// Setting mountBehavior to undefined prevents automatic location fetching on mount
const { data, loading, get } = useGeolocation({
mountBehavior: undefined
});
return (
<div>
<button onClick={get} disabled={loading}>
{loading ? 'Loading...' : 'Get Current Location'}
</button>
{data && (
<p>Latitude: {data.latitude}, Longitude: {data.longitude}</p>
)}
</div>
);
};
Setting Timeout and High Accuracy Optionsโ
typescript
import { useGeolocation } from '@modern-kit/react';
const PreciseLocation = () => {
const { data, error } = useGeolocation({
enableHighAccuracy: true, // Use GPS
timeout: 10000, // 10 second timeout
maximumAge: 60000, // Allow cached location up to 1 minute
});
if (error) {
return <div>Unable to get location: {error.message}</div>;
}
return data ? (
<div>Precise location: {data.latitude}, {data.longitude}</div>
) : null;
};
Exampleโ
๐งช How to test
- Allow location access in your browser
- Click the 'Get Current Location' button to view your location
- Use the 'Start Real-Time Tracking' button to track location changes
โณ Loading...โธ Tracking stopped
๐ก Note: Location accuracy may vary depending on the browser and device. Using the
enableHighAccuracy: trueoption enables GPS for more accurate positioning.