import { useState, useEffect, useRef } from "preact/hooks"; export interface UserLocation { lat: number; lng: number; accuracy: number; heading: number | null; speed: number | null; timestamp: number; } export function useLocation() { const [location, setLocation] = useState(null); const [error, setError] = useState(null); const watchId = useRef(null); useEffect(() => { if (!navigator.geolocation) { setError("Geolocation not supported"); return; } watchId.current = navigator.geolocation.watchPosition( (pos) => { setLocation({ lat: pos.coords.latitude, lng: pos.coords.longitude, accuracy: pos.coords.accuracy, heading: pos.coords.heading, speed: pos.coords.speed, timestamp: pos.timestamp, }); setError(null); }, (err) => { setError(err.message); }, { enableHighAccuracy: true, maximumAge: 10000, timeout: 15000, } ); return () => { if (watchId.current !== null) { navigator.geolocation.clearWatch(watchId.current); } }; }, []); return { location, error }; }