useGeolocation

A React Hook that provides a simple way to get the user's geolocation.

Demo

Source
Is supported:
false
Is locating:
false
Located at:
09:56:04

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const geo = useGeolocation(options)

Options

/**
 * DOM built-in Geolocation API options
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#options
 */
interface PositionOptions {
  enableHighAccuracy?: boolean
  maximumAge?: number
  timeout?: number
}

export type UseGeolocationOptions = PositionOptions & {
  /**
   * Whether to start watching the geolocation immediately.
   *
   * @defaultValue true
   */
  immediate?: boolean
}

Returns

export type UseGeolocationReturns = Pausable & {
  /**
   * Whether the geolocation API is supported.
   */
  isSupported: boolean
  /**
   * The current latitude.
   */
  latitude: number | null
  /**
   * The current longitude.
   */
  longitude: number | null
  /**
   * The current geolocation state.
   */
  isLocating: boolean
  /**
   * The timestamp when the geolocation was last updated.
   */
  locatedAt: number | null
  /**
   * The error object if any.
   */
  error: GeolocationPositionError | null
  /**
   * The current geolocation coordinates.
   */
  coords: Omit<GeolocationPosition['coords'], 'latitude' | 'longitude'> & {
    latitude: number | null
    longitude: number | null
  }
}