Skip to main content

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โ€‹

๐Ÿ”— View source 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โ€‹

NameTypeDefaultDescription
enableHighAccuracybooleanfalseWhether to request high-accuracy location (uses GPS, increases battery usage)
timeoutnumberInfinityMaximum time allowed to obtain location information (milliseconds)
maximumAgenumber0Maximum age of cached location information (milliseconds)
mountBehavior'watch' | 'get''get'How to fetch location when the hook mounts

Returnsโ€‹

NameTypeDescription
dataGeolocationData | nullLocation data (latitude, longitude, accuracy, altitude, timestamp, etc.)
errorGeolocationPositionError | Error | nullError information
loadingbooleanWhether location information is being fetched
isWatchingbooleanWhether real-time location tracking is active
get() => voidFunction to fetch the current location once
watch() => voidFunction to start real-time location tracking
stopWatch() => voidFunction to stop real-time location tracking

GeolocationDataโ€‹

NameTypeDescription
latitudenumberLatitude
longitudenumberLongitude
accuracynumberLocation accuracy (meters)
altitudenumber | nullAltitude (meters)
altitudeAccuracynumber | nullAltitude accuracy (meters)
headingnumber | nullDirection of movement (0ยฐโ€“360ยฐ, north-based)
speednumber | nullMovement speed (m/s)
timestampnumberTime when location was acquired

Remarksโ€‹

Caution
  • HTTPS required: The Geolocation API only works in HTTPS environments for security reasons. (localhost is 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.geolocation does not exist; the hook detects this and returns an error.
  • Battery usage: Using enableHighAccuracy: true provides 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 access
  • POSITION_UNAVAILABLE (code: 2): Location information is unavailable
  • TIMEOUT (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

  1. Allow location access in your browser
  2. Click the 'Get Current Location' button to view your location
  3. 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 theenableHighAccuracy: trueoption enables GPS for more accurate positioning.