Docs
useGeolocation

Access and monitor a user's geolocation (after they give permission) with useGeolocation.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-geolocation

Usage

"use client"
 
import useGeolocation from "@/hooks/use-geolocation"
 
export function Component() {
  const {
    loading,
    error,
    latitude,
    longitude,
    altitude,
    accuracy,
    altitudeAccuracy,
    heading,
    speed,
    timestamp,
  } = useGeolocation({
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0,
  })
 
  if (loading) {
    return <div>Loading geolocation data...</div>
  }
 
  if (error) {
    return <div>Error: {error.message}</div>
  }
 
  return (
    <div>
      <h2>Geolocation Data</h2>
      <p>Latitude: {latitude!.toFixed(6)}</p>
      <p>Longitude: {longitude!.toFixed(6)}</p>
      <p>Accuracy: {accuracy} meters</p>
 
      {altitude && <p>Altitude: {altitude} meters</p>}
      {altitudeAccuracy && <p>Altitude Accuracy: {altitudeAccuracy} meters</p>}
      {heading && <p>Heading: {heading}° from true north</p>}
      {speed && <p>Speed: {speed} m/s</p>}
 
      <p>Last updated: {new Date(timestamp!).toLocaleTimeString()}</p>
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
optionsobjectThis is an optional configuration object provided when calling useGeolocation. It is used when calling navigator.geolocation.getCurrentPosition() and navigator.geolocation.watchPosition(). Some of the attributes it accepts are enableHighAccuracy, timeout, and maximumAge.{ enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }Yes

Return Values

NameTypeDescription
loadingbooleanA boolean indicating if the geolocation data is currently being fetched.
accuracynumberThe accuracy of the latitude and longitude properties in meters.
altitudenumberThe altitude in meters above the mean sea level.
altitudeAccuracynumber`The accuracy of altitude in meters.
headingnumberThe direction in which the device is traveling. This value, specified in degrees, indicates how far off from heading true north the device is.
latitudenumberThe latitude in decimal degrees.
longitudenumberThe longitude in decimal degrees.
speednumberThe current ground speed of the device, specified in meters per second.
timestampnumberThe timestamp at which the geolocation data was retrieved.
errorobjectAn error object, if an error occurred while retrieving the geolocation data.
requestGeolocationFunctionA function that can be called to request the user's geolocation data.
retryFunctionA function that can be called to retry fetching the geolocation data.