useGeolocation()
The useGeolocation()
hook provides access to the user's current geographical location using the browser's Geolocation API.
Import
import { useGeolocation } from 'react-haiku';
Usage
Loading...
import { useGeolocation } from 'react-haiku';
export const Component = () => {
const { latitude, longitude, error, loading } = useGeolocation({
enableHighAccuracy: true,
timeout: 10000,
});
if (loading) {
return <div>Getting your location...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
<p>Latitude: {latitude}</p>
<p>Longitude: {longitude}</p>
</div>
);
};
API
This hook accepts an optional configuration object with the following properties:
enableHighAccuracy
- boolean to request the most accurate results possible, defaults tofalse
timeout
- maximum time in milliseconds to wait before timeout, defaults to5000
maximumAge
- maximum age of cached position in milliseconds, defaults to0
watch
- boolean to continuously watch for position changes, defaults tofalse
The hook returns an object with:
latitude
- the latitude coordinate ornull
longitude
- the longitude coordinate ornull
error
- error object withcode
andmessage
properties, ornull
loading
- boolean indicating if the request is in progress