useGeolocation

Track user geolocation.

https://www.shaktools.com/shak-hooks
Sensor

API Reference

Installation

terminal
pnpm add @shak-hooks/usehooks
import.ts
import { useGeolocation } from "@shak-hooks/usehooks";
Source: packages/react/src/useGeolocation.ts

Signature

signature.ts
export function useGeolocation(options?: PositionOptions)

Parameters

NameTypeOptionalDefault
optionsPositionOptionsYes-

Returns

unknown

Implementation

use-geolocation.ts
1import { useState, useEffect } from "react";
2
3interface GeolocationState {
4 loading: boolean;
5 accuracy: number | null;
6 altitude: number | null;
7 altitudeAccuracy: number | null;
8 heading: number | null;
9 latitude: number | null;
10 longitude: number | null;
11 speed: number | null;
12 timestamp: number | null;
13 error: GeolocationPositionError | null;
14}
15
16export function useGeolocation(options?: PositionOptions): GeolocationState {
17 const [state, setState] = useState<GeolocationState>({
18 loading: true,
19 accuracy: null,
20 altitude: null,
21 altitudeAccuracy: null,
22 heading: null,
23 latitude: null,
24 longitude: null,
25 speed: null,
26 timestamp: null,
27 error: null,
28 });
29
30 useEffect(() => {
31 const onEvent = ({ coords, timestamp }: GeolocationPosition) => {
32 setState({
33 loading: false,
34 timestamp,
35 latitude: coords.latitude,
36 longitude: coords.longitude,
37 altitude: coords.altitude,
38 accuracy: coords.accuracy,
39 altitudeAccuracy: coords.altitudeAccuracy,
40 heading: coords.heading,
41 speed: coords.speed,
42 error: null,
43 });
44 };
45
46 const onError = (error: GeolocationPositionError) => {
47 setState((s) => ({ ...s, loading: false, error }));
48 };
49
50 navigator.geolocation.getCurrentPosition(onEvent, onError, options);
51 const watchId = navigator.geolocation.watchPosition(onEvent, onError, options);
52
53 return () => navigator.geolocation.clearWatch(watchId);
54 }, [options]);
55
56 return state;
57}

Advertisement

Google Ads

Usage

example.tsx
1import { useGeolocation } from "@shak-hooks/usehooks";
2
3const result = useGeolocation(undefined);
4// result: unknown
5// Use values directly (React state).

Let‘s do great work together

Empowering creators with free, high-performance AI, SEO, and developer tools. Join thousands of users optimizing their workflow with Shak-Tools.

Tools10+ Free
UsersGlobal

Stay in the loop

Join our newsletter for the latest AI tools and updates.

ShakTools
© 2025 Shaktools. All Rights Reserved.Privacy Policy