hooks
useGeolocation

useGeolocation

A custom hook that provides functionalities for accessing and managing geolocation data.

Add hook

Create a file use-geolocation.ts and copy & paste the code from useGeolocation.

Hook

import { useState, useEffect, useCallback } from 'react'
 
type Coordinates = {
    latitude: number | null
    longitude: number | null
}
 
type GeolocationError = {
    code: number
    message: string
} | null
 
type GeolocationOptions = {
    enableHighAccuracy?: boolean
    timeout?: number
    maximumAge?: number
}
 
export const useGeolocation = (options?: GeolocationOptions) => {
    const [coordinates, setCoordinates] = useState<Coordinates>({
        latitude: null,
        longitude: null,
    })
 
    const [error, setError] = useState<GeolocationError>(null)
 
    const handleSuccess = (position: GeolocationPosition) => {
        const { latitude, longitude } = position.coords
        setCoordinates({ latitude, longitude })
        setError(null)
    }
 
    const handleError = (error: GeolocationPositionError) => {
        setError({
            code: error.code,
            message: error.message,
        })
    }
 
    const getCurrentPosition = useCallback(() => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(handleSuccess, handleError, options)
        } else {
            setError({
                code: 0,
                message: 'Geolocation is not supported by your browser.',
            })
        }
    }, [options])
 
    useEffect(() => {
        getCurrentPosition()
    }, [getCurrentPosition])
 
    return { coordinates, error, refresh: getCurrentPosition }
}

Usage

import React from 'react';
import { useGeolocation } from './hooks/use-geolocation';
 
function GeolocationComponent() {
    const { coordinates, error, refresh } = useGeolocation();
 
    if (error) {
        return <div>Error: {error.message}</div>;
    }
 
    return (
        <div>
            <h1>Geolocation Demo</h1>
            {coordinates.latitude && coordinates.longitude ? (
                <p>
                    Latitude: {coordinates.latitude}, Longitude: {coordinates.longitude}
                </p>
            ) : (
                <p>Loading location...</p>
            )}
            <button onClick={refresh}>Refresh Location</button>
        </div>
    );
}
 
export default GeolocationComponent;

API

Returns

NameDescription
coordinatesAn object containing the current latitude and longitude.
errorAn object containing error information if geolocation fails.
refreshA function to manually refresh the geolocation.

Contributors

Avatar 1