| import { useCallback, useState } from "react"; |
|
|
| export interface GeoState { |
| lat: number | null; |
| lon: number | null; |
| error: string | null; |
| loading: boolean; |
| } |
|
|
| |
| export const DEFAULT_CENTER: [number, number] = [18.5204, 73.8567]; |
|
|
| export function useGeolocation() { |
| const [state, setState] = useState<GeoState>({ |
| lat: null, |
| lon: null, |
| error: null, |
| loading: false, |
| }); |
|
|
| const request = useCallback((): Promise<{ lat: number; lon: number } | null> => { |
| return new Promise((resolve) => { |
| if (!("geolocation" in navigator)) { |
| setState((s) => ({ ...s, error: "Geolocation not supported" })); |
| resolve(null); |
| return; |
| } |
| setState((s) => ({ ...s, loading: true, error: null })); |
| navigator.geolocation.getCurrentPosition( |
| (pos) => { |
| const lat = pos.coords.latitude; |
| const lon = pos.coords.longitude; |
| setState({ lat, lon, error: null, loading: false }); |
| resolve({ lat, lon }); |
| }, |
| (err) => { |
| setState((s) => ({ ...s, loading: false, error: err.message })); |
| resolve(null); |
| }, |
| { enableHighAccuracy: true, timeout: 8000 }, |
| ); |
| }); |
| }, []); |
|
|
| return { ...state, request }; |
| } |
|
|