API Reference
useGeolocation

useGeolocation

The useGeolocation hook allows you to easily track the user's current location using the browser's geolocation API. It returns an object containing the current latitude, longitude, and an optional error message if any issues arise during the geolocation retrieval process.

Installation

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useGeolocation into your component.

import { useGeolocation } from '@ridgehkr/useful'

Example

The following is a basic example where useGeolocation is used to query the browser's location API and display the user's latitude and longitude. The getLocation function is used to trigger the location retrieval process, and the location object contains the current latitude, longitude, and any error messages.

LocationComponent.tsx
import { useGeolocation } from '@ridgehkr/useful'
 
function LocationComponent() {
  const { location, getLocation } = useGeolocation()
 
  // Trigger getLocation to update the user's location
  const handleButtonClick = () => {
    getLocation()
  }
 
  return (
    <div>
      <p>Latitude: {location.latitude}</p>
      <p>Longitude: {location.longitude}</p>
      {location.error && <p>Error: {location.error}</p>}
      <button onClick={handleButtonClick}>Get Location</button>
    </div>
  )
}

API Reference

Hook Signature

useGeolocation(): GeoLocationState

Parameters

useGeolocation does not accept any parameters.

Return Value

useGeolocation returns a GeoLocationState object with the following properties:

PropertyTypeDescription
locationGeoLocationThe user's location details, or an error message if they could not be retrieved
getLocation() => voidA function to trigger the location retrieval process

GeoLocation Type

PropertyTypeDescription
latitudenumberThe user's current latitude
longitudenumberThe user's current longitude
errorstringAn error message if retrieval fails