React hook for following a browser geolocation
React hook usePosition()
allows you to fetch client’s browser geolocation and/or subscribe to all further geolocation changes.
▶︎ Storybook demo of usePosition()
hook.
Using yarn
:
yarn add use-position
Using npm
:
npm i use-position --save
Import the hook:
import { usePosition } from 'use-position';
const {
latitude,
longitude,
timestamp,
accuracy,
error,
} = usePosition();
In this case if browser detects geolocation change the latitude
, longitude
and timestamp
values will be updated.
const watch = true;
const {
latitude,
longitude,
timestamp,
accuracy,
error,
} = usePosition(watch);
The second parameter of usePosition()
hook is position options.
const watch = true;
const {
latitude,
longitude,
timestamp,
accuracy,
error,
} = usePosition(watch, {enableHighAccuracy: true});
import React from 'react';
import { usePosition } from 'use-position';
export const Demo = () => {
const watch = true;
const {
latitude,
longitude,
timestamp,
accuracy,
error,
} = usePosition(watch);
return (
<code>
latitude: {latitude}<br/>
longitude: {longitude}<br/>
timestamp: {timestamp}<br/>
accuracy: {accuracy && `${accuracy}m`}<br/>
error: {error}
</code>
);
};
usePosition()
inputwatch: boolean
- set it to true
to follow the location.settings: object
- position options
settings.enableHighAccuracy
- indicates the application would like to receive the most accurate results (default false
),settings.timeout
- maximum length of time (in milliseconds) the device is allowed to take in order to return a position (default Infinity
),settings.maximumAge
- the maximum age in milliseconds of a possible cached position that is acceptable to return (default 0
).usePosition()
outputlatitude: number
- latitude (i.e. 52.3172414
),longitude: number
- longitude (i.e. 4.8717809
),timestamp: number
- timestamp when location was detected (i.e. 1561815013194
),accuracy: number
- location accuracy in meters (i.e. 24
),error: string
- error message or null
(i.e. User denied Geolocation
)Author: trekhleb
Live Demo: https://trekhleb.github.io/use-position/
GitHub: https://github.com/trekhleb/use-position
#reactjs #javascript #react hook