← Back to all hooks

useGeolocation

Track user's geographic position in real-time using the Geolocation API. Automatically cleans up when component unmounts.

Live Demo

Click "Allow" when prompted to share your location. The hook will track your position in real-time.

📍

Requesting location access...

Please allow location access when prompted

Code Examples

Basic Usage

import { useGeolocation } from "@uiblock/hooks";

export default function LocationTracker() {
  const { latitude, longitude, error, loading } = useGeolocation();

  if (loading) return <p>Loading location...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      <p>Latitude: {latitude}</p>
      <p>Longitude: {longitude}</p>
    </div>
  );
}

With High Accuracy

import { useGeolocation } from "@uiblock/hooks";

export default function PreciseLocation() {
  const location = useGeolocation({
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
  });

  return (
    <div>
      <p>Lat: {location.latitude?.toFixed(6)}</p>
      <p>Lng: {location.longitude?.toFixed(6)}</p>
      <p>Accuracy: {location.accuracy?.toFixed(2)}m</p>
      {location.speed && <p>Speed: {location.speed} m/s</p>}
    </div>
  );
}

Display on Map

import { useGeolocation } from "@uiblock/hooks";

export default function MapView() {
  const { latitude, longitude, loading } = useGeolocation();

  if (loading) return <p>Getting your location...</p>;

  const mapUrl = `https://www.openstreetmap.org/?mlat=${latitude}&mlon=${longitude}&zoom=15`;

  return (
    <div>
      <p>Your location:</p>
      <a href={mapUrl} target="_blank">View on Map</a>
    </div>
  );
}

How It Works

Here's the complete implementation of the useGeolocation hook:

import { useState, useEffect } from 'react'

export function useGeolocation(options?: PositionOptions) {
  const [state, setState] = useState({
    latitude: null,
    longitude: null,
    accuracy: null,
    error: null,
    loading: true
  })

  useEffect(() => {
    if (!navigator.geolocation) {
      setState(prev => ({
        ...prev,
        loading: false,
        error: 'Geolocation not supported'
      }))
      return
    }

    const onSuccess = (position) => {
      setState({
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        accuracy: position.coords.accuracy,
        error: null,
        loading: false
      })
    }

    const onError = (error) => {
      setState(prev => ({
        ...prev,
        loading: false,
        error: error.message
      }))
    }

    // Watch position for real-time updates
    const watchId = navigator.geolocation.watchPosition(
      onSuccess,
      onError,
      options
    )

    // Cleanup: stop watching on unmount
    return () => {
      navigator.geolocation.clearWatch(watchId)
    }
  }, [options])

  return state
}

Key Points:

  • watchPosition() continuously tracks location changes
  • clearWatch() stops tracking when component unmounts
  • Handles loading, error, and success states
  • Returns all position data (lat, lng, accuracy, speed, etc.)

API Reference

Parameters

options?: UseGeolocationOptions

Optional configuration object

  • enableHighAccuracy: boolean - Request high accuracy (uses GPS)
  • timeout: number - Maximum time (ms) to wait for position
  • maximumAge: number - Maximum age (ms) of cached position

Returns

latitude - Latitude in decimal degrees

longitude - Longitude in decimal degrees

accuracy - Accuracy in meters

altitude - Altitude in meters (if available)

speed - Speed in meters per second (if available)

heading - Direction of travel in degrees (if available)

error - Error message if location access fails

loading - Boolean indicating if location is being fetched

Important Notes

  • User Permission: Browser will prompt user to allow location access
  • HTTPS Required: Geolocation API only works on secure contexts (HTTPS)
  • Battery Usage: High accuracy mode uses GPS and drains battery faster
  • Auto Cleanup: Hook automatically stops watching position on unmount

💡 Use Cases

  • Location-based services and recommendations
  • Delivery and ride-sharing apps
  • Fitness and running trackers
  • Store locators and "near me" features
  • Weather apps showing local conditions
  • Geotagging photos and posts
  • Emergency services and safety apps