Skip to main content

useGeolocation

A hook that wraps the browser's Geolocation API with loading and error state.

The hook​

useGeolocation.ts
import { useState } from 'react';

interface Position {
lat: number;
lng: number;
}

export const useGeolocation = (): {
isLoading: boolean;
position: Position;
error: string;
getPosition: () => void;
} => {
const [isLoading, setIsLoading] = useState(false);
const [position, setPosition] = useState({} as Position);
const [error, setError] = useState('');

const getPosition = () => {
if (!navigator.geolocation) {
return setError('Your browser does not support geolocation');
}

setIsLoading(true);

navigator.geolocation.getCurrentPosition(
(pos) => {
setPosition({
lat: pos.coords.latitude,
lng: pos.coords.longitude,
});

setIsLoading(false);
},
(error) => {
setError(error.message);
setIsLoading(false);
},
);
};

return { isLoading, position, error, getPosition };
};

Try it​

Click the button — your browser will ask for permission, then show your real coordinates: