useGeolocation
Hook to use user's geographic location.
See: GeoLocation API.
Demo
INFO
The component displays geographic location info.
Loading demo…
Show source code
tsx
import { useState } from "react";
import { useGeolocation } from "../../../.."
export const UseGeolocation = () => {
const [error, setError] = useState("")
const [location, currentPosition] = useGeolocation({
mode: "manual",
onError(error) {
setError(error.message);
}
});
return (<div style={{ textAlign: "left", width: 'fit-content', margin:'0 auto' }}>
{
error && <p style={{ color: 'red' }}>{error}</p>
}
<br/>
<button onClick={currentPosition}>Get Location</button>
<br />
<p >isSupported: {location.isSupported ? "true" : "false"}</p>
<p >Timestamp: {location?.position?.timestamp}</p>
<p >Coords:</p>
<div style={{paddingLeft: 10, textAlign: 'left', width: 'fit-content', margin: '0 auto'}}>
<p>accuracy: {location.position?.coords.accuracy}</p>
<p>altitude: {location.position?.coords.altitude}</p>
<p>altitudeAccuracy: {location.position?.coords.altitudeAccuracy}</p>
<p>heading: {location.position?.coords.heading}</p>
<p>latitude: {location.position?.coords.latitude}</p>
<p>longitude: {location.position?.coords.longitude}</p>
<p>speed: {location.position?.coords.speed}</p>
</div>
</div>)
}Types
UseGeolocationProps
Props accepted by useGeolocation.
| Property | Type | Required | Description |
|---|---|---|---|
mode | "observe" \| "current" \| "manual" | ✓ | it establishes how to obtain the geographic location: - current: it gets the location when invoked. - observer: it gets the current position every time it changes. - manual: to obtain the location it need to invoke functions returned from hook. |
onError | (error: GeolocationPositionError) => void | Called when the Geolocation API returns an error (permission denied, unavailable, timeout, etc.). | |
locationOptions | PositionOptions | Options forwarded directly to Geolocation.getCurrentPosition / Geolocation.watchPosition. Common options: { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }. |
UseGeoLocationResult
Result tuple returned by useGeolocation.
| Index | Type | Description |
|---|---|---|
[0] | ({ isSupported: true; position?: GeolocationPosition; }) \| ({ isSupported: false; position?: never; }) | location - possible states of the Geolocation API: supported (with an optional position) or not supported. |
[1] | () => Promise<void> | currentPosition — function to obtain manually current location. |
[2] | () => Promise<()=>void> | observerPosition — function to obtain location on every changes. |
