Skip to content

useGeolocation

Hook that returns the current geolocation

browser
medium
test coverage
Last changed: 13 days ago

TIP

This hook uses navigator.geolocation browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation

Library
CLI
Manual
typescript
import { useGeolocation } from '@siberiacancode/reactuse';

Usage

typescript
const { loading, error, timestamp, accuracy, latitude, longitude, altitude, altitudeAccuracy, heading, speed } = useGeolocation((position) => console.log(position));
// or
const { loading, error, timestamp, accuracy, latitude, longitude, altitude, altitudeAccuracy, heading, speed } = useGeolocation();

Demo

Api

Parameters

NameTypeDefaultNote
callback?UseGeolocationCallback-The callback function to be invoked when geolocation changes
params.enableHighAccuracy?boolean-Enable high accuracy
params.maximumAge?number-Maximum age
params.timeout?number-Timeout

Returns

UseGeolocationReturn

Parameters

NameTypeDefaultNote
options?UseGeolocationOptions-Configuration options
options.onChange?(position: GeolocationPosition) => void-The callback function to be invoked when geolocation changes
options.onError?(error: GeolocationPositionError) => void-The callback function to be invoked on geolocation error
options.enableHighAccuracy?boolean-Enable high accuracy
options.maximumAge?number-Maximum age
options.timeout?number-Timeout

Returns

UseGeolocationReturn

Type declaration

typescript
export interface UseGeolocationReturn {
  /** The accuracy of the last position update */
  accuracy: number | null;
  /** The altitude of the last position update */
  altitude: number | null;
  /** The altitude accuracy of the last position update */
  altitudeAccuracy: number | null;
  /** The error of the last position update */
  error: GeolocationPositionError | null;
  /** The heading of the last position update */
  heading: number | null;
  /** The latitude of the last position update */
  latitude: number | null;
  /** The loading state */
  loading: boolean;
  /** The longitude of the last position update */
  longitude: number | null;
  /** The speed of the last position update */
  speed: number | null;
  /** The timestamp of the last position update */
  timestamp: number | null;
}

export type UseGeolocationCallback = (position: GeolocationPosition) => void;

export interface UseGeolocationOptions extends PositionOptions {
  /** The callback function to be invoked when the geolocation changes */
  onChange?: UseGeolocationCallback;
  /** The callback function to be invoked when geolocation errors */
  onError?: (error: GeolocationPositionError) => void;
}

export interface UseGeolocation {
  (callback?: UseGeolocationCallback, options?: PositionOptions): UseGeolocationReturn;

  (options?: UseGeolocationOptions): UseGeolocationReturn;
}

Source

SourceDemo

Contributors

D
debabin
debabin
Z
zeroqs
zeroqs

Released under the MIT License.