All files / use-geolocation/src useGeolocation.ts

92.66% Statements 101/109
93.47% Branches 43/46
100% Functions 20/20
92.66% Lines 101/109

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422                                                                                                                                                                                                                                        76x     76x 76x 76x 76x       76x       76x 76x 76x 76x     76x 76x 76x 76x     76x     76x             76x 4x         4x   1x 1x 1x   2x 2x 2x   1x 1x 1x           4x           4x 4x       76x   7x 7x     7x                         7x 7x           76x   14x 1x       1x 1x 1x     13x 13x   13x               76x 78x 10x 10x         76x   10x                     10x   10x 10x     10x 2x     2x                         2x     10x               76x 34x             34x 2x 2x             76x 31x         31x 31x   31x     1x 1x   1x 1x 1x 1x     1x       30x     31x 31x 1x           76x 31x 6x             76x 31x 4x     31x 31x             76x 31x 31x           76x   2x 1x     1x                     76x   2x 1x     1x                     76x                          
import { useCallback, useEffect, useRef, useState } from "react";
import type {
  GeolocationError,
  GeolocationErrorCode,
  GeoPosition,
  PermissionState,
  UseGeolocationOptions,
  UseGeolocationReturn,
} from "./types";
import { calculateBearing, haversineDistance } from "./utils";
 
/**
 * A React hook for accessing device geolocation with real-time tracking and distance calculation.
 *
 * Features:
 * - Get current position (one-time)
 * - Watch position for real-time updates
 * - Permission state tracking
 * - Distance calculation using Haversine formula
 * - Bearing/direction calculation
 * - SSR compatible
 * - TypeScript support
 *
 * @param options - Configuration options
 * @returns Geolocation state and control functions
 *
 * @example
 * ```tsx
 * // Basic usage - get current position
 * function MyLocation() {
 *   const { position, loading, error } = useGeolocation();
 *
 *   if (loading) return <p>Loading location...</p>;
 *   if (error) return <p>Error: {error.message}</p>;
 *   if (!position) return <p>No position yet</p>;
 *
 *   return (
 *     <div>
 *       <p>Latitude: {position.coords.latitude}</p>
 *       <p>Longitude: {position.coords.longitude}</p>
 *       <p>Accuracy: {position.coords.accuracy}m</p>
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Real-time tracking with watch
 * function LiveTracking() {
 *   const { position, watchPosition, clearWatch } = useGeolocation({
 *     immediate: false,
 *     watch: false,
 *   });
 *
 *   return (
 *     <div>
 *       <button onClick={watchPosition}>Start Tracking</button>
 *       <button onClick={clearWatch}>Stop Tracking</button>
 *       {position && (
 *         <p>Current: {position.coords.latitude}, {position.coords.longitude}</p>
 *       )}
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Distance calculation
 * function DistanceToDestination() {
 *   const { position, distanceFrom } = useGeolocation();
 *
 *   // New York City coordinates
 *   const nyLat = 40.7128;
 *   const nyLon = -74.0060;
 *
 *   const distance = distanceFrom(nyLat, nyLon);
 *
 *   return (
 *     <div>
 *       {distance && (
 *         <p>Distance to NYC: {(distance / 1000).toFixed(2)} km</p>
 *       )}
 *     </div>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With callbacks and high accuracy
 * const geolocation = useGeolocation({
 *   enableHighAccuracy: true,
 *   timeout: 10000,
 *   onSuccess: (pos) => console.log('Got position:', pos),
 *   onError: (err) => console.error('Geolocation error:', err),
 *   onPositionChange: (pos) => console.log('Position updated:', pos),
 *   onPermissionChange: (state) => console.log('Permission:', state),
 * });
 * ```
 */
export function useGeolocation(
  options: UseGeolocationOptions = {}
): UseGeolocationReturn {
  // ============ Parse Options ============
  const {
    enableHighAccuracy = false,
    maximumAge = 0,
    timeout = 30000, // Default 30 seconds
    watch = false,
    immediate = true,
    onSuccess,
    onError,
    onPositionChange,
    onPermissionChange,
  } = options;
 
  // ============ State ============
  const [position, setPosition] = useState<GeoPosition | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<GeolocationError | null>(null);
  const [permission, setPermission] = useState<PermissionState>("unavailable");
 
  // ============ Check Support ============
  const isSupported =
    typeof navigator !== "undefined" && "geolocation" in navigator;
 
  // ============ Refs for Callbacks ============
  // Store callbacks in refs to avoid re-registering listeners when they change
  const onSuccessRef = useRef(onSuccess);
  const onErrorRef = useRef(onError);
  const onPositionChangeRef = useRef(onPositionChange);
  const onPermissionChangeRef = useRef(onPermissionChange);
 
  // Update callback refs on every render
  onSuccessRef.current = onSuccess;
  onErrorRef.current = onError;
  onPositionChangeRef.current = onPositionChange;
  onPermissionChangeRef.current = onPermissionChange;
 
  // ============ Refs for Watch Management ============
  const watchIdRef = useRef<number | null>(null);
 
  // ============ Refs for Options ============
  const optionsRef = useRef<PositionOptions>({
    enableHighAccuracy,
    maximumAge,
    timeout,
  });
 
  // ============ Error Handler ============
  const handleError = useCallback((nativeError: GeolocationPositionError) => {
    setLoading(false);
 
    let errorCode: GeolocationErrorCode;
    let errorMessage: string;
 
    switch (nativeError.code) {
      case nativeError.PERMISSION_DENIED:
        errorCode = "PERMISSION_DENIED";
        errorMessage = "User denied geolocation permission";
        break;
      case nativeError.POSITION_UNAVAILABLE:
        errorCode = "POSITION_UNAVAILABLE";
        errorMessage = "Position information unavailable";
        break;
      case nativeError.TIMEOUT:
        errorCode = "TIMEOUT";
        errorMessage = "Position request timed out";
        break;
      default:
        errorCode = "POSITION_UNAVAILABLE";
        errorMessage = "Unknown error occurred";
    }
 
    const geolocationError: GeolocationError = {
      code: errorCode,
      message: errorMessage,
      nativeError,
    };
 
    setError(geolocationError);
    onErrorRef.current?.(geolocationError);
  }, []);
 
  // ============ Success Handler ============
  const handleSuccess = useCallback(
    (nativePosition: globalThis.GeolocationPosition) => {
      setLoading(false);
      setError(null);
 
      // Convert to plain object to avoid issues with frozen/readonly native object
      const geoPosition: GeoPosition = {
        coords: {
          latitude: nativePosition.coords.latitude,
          longitude: nativePosition.coords.longitude,
          altitude: nativePosition.coords.altitude,
          accuracy: nativePosition.coords.accuracy,
          altitudeAccuracy: nativePosition.coords.altitudeAccuracy,
          heading: nativePosition.coords.heading,
          speed: nativePosition.coords.speed,
        },
        timestamp: nativePosition.timestamp,
      };
 
      setPosition(geoPosition);
      onSuccessRef.current?.(geoPosition);
    },
    []
  );
 
  // ============ getCurrentPosition ============
  const getCurrentPosition = useCallback(() => {
    // Check support dynamically in case it changes
    if (typeof navigator === "undefined" || !navigator.geolocation) {
      const notSupportedError: GeolocationError = {
        code: "NOT_SUPPORTED",
        message: "Geolocation is not supported in this environment",
      };
      setError(notSupportedError);
      onErrorRef.current?.(notSupportedError);
      return;
    }
 
    setLoading(true);
    setError(null);
 
    navigator.geolocation.getCurrentPosition(
      handleSuccess,
      handleError,
      optionsRef.current
    );
  }, [handleSuccess, handleError]);
 
  // ============ clearWatch ============
  const clearWatch = useCallback(() => {
    if (watchIdRef.current !== null && typeof navigator !== "undefined") {
      navigator.geolocation.clearWatch(watchIdRef.current);
      watchIdRef.current = null;
    }
  }, []);
 
  // ============ watchPosition ============
  const watchPosition = useCallback(() => {
    // Check support dynamically in case it changes
    Iif (typeof navigator === "undefined" || !navigator.geolocation) {
      const notSupportedError: GeolocationError = {
        code: "NOT_SUPPORTED",
        message: "Geolocation is not supported in this environment",
      };
      setError(notSupportedError);
      onErrorRef.current?.(notSupportedError);
      return;
    }
 
    // Clear existing watch if any
    clearWatch();
 
    setLoading(true);
    setError(null);
 
    // Success handler for watch includes onPositionChange callback
    const handleWatchSuccess = (nativePosition: globalThis.GeolocationPosition) => {
      handleSuccess(nativePosition);
 
      // Convert to plain object for callback
      const geoPosition: GeoPosition = {
        coords: {
          latitude: nativePosition.coords.latitude,
          longitude: nativePosition.coords.longitude,
          altitude: nativePosition.coords.altitude,
          accuracy: nativePosition.coords.accuracy,
          altitudeAccuracy: nativePosition.coords.altitudeAccuracy,
          heading: nativePosition.coords.heading,
          speed: nativePosition.coords.speed,
        },
        timestamp: nativePosition.timestamp,
      };
 
      onPositionChangeRef.current?.(geoPosition);
    };
 
    watchIdRef.current = navigator.geolocation.watchPosition(
      handleWatchSuccess,
      handleError,
      optionsRef.current
    );
  }, [handleSuccess, handleError, clearWatch]);
 
  // ============ Update Options Ref & Auto-Restart Watch ============
  useEffect(() => {
    optionsRef.current = {
      enableHighAccuracy,
      maximumAge,
      timeout,
    };
 
    // If currently watching, restart with new options
    if (watchIdRef.current !== null) {
      clearWatch();
      watchPosition();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [enableHighAccuracy, maximumAge, timeout]);
  // Note: clearWatch and watchPosition are intentionally omitted to avoid infinite loop
 
  // ============ Permission Monitoring ============
  useEffect(() => {
    Iif (typeof navigator === "undefined" || !navigator.permissions) {
      setPermission("unavailable");
      return;
    }
 
    let permissionStatus: PermissionStatus | null = null;
    let changeHandler: (() => void) | null = null;
 
    navigator.permissions
      .query({ name: "geolocation" as PermissionName })
      .then((status) => {
        permissionStatus = status;
        setPermission(status.state as PermissionState);
 
        changeHandler = () => {
          const newState = status.state as PermissionState;
          setPermission(newState);
          onPermissionChangeRef.current?.(newState);
        };
 
        status.addEventListener("change", changeHandler);
      })
      .catch(() => {
        // Permissions API not supported or query failed
        setPermission("unavailable");
      });
 
    return () => {
      if (permissionStatus && changeHandler) {
        permissionStatus.removeEventListener("change", changeHandler);
      }
    };
  }, []);
 
  // ============ Immediate Fetch on Mount ============
  useEffect(() => {
    if (immediate && isSupported) {
      getCurrentPosition();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [immediate, isSupported]);
  // getCurrentPosition is intentionally omitted to run only once on mount
 
  // ============ Watch on Mount ============
  useEffect(() => {
    if (watch && isSupported) {
      watchPosition();
    }
 
    return () => {
      clearWatch();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [watch, isSupported]);
  // watchPosition and clearWatch are intentionally omitted to run only once on mount
 
  // ============ Cleanup on Unmount ============
  useEffect(() => {
    return () => {
      clearWatch();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
 
  // ============ Utility: distanceFrom ============
  const distanceFrom = useCallback(
    (latitude: number, longitude: number): number | null => {
      if (!position) {
        return null;
      }
 
      return haversineDistance(
        position.coords.latitude,
        position.coords.longitude,
        latitude,
        longitude
      );
    },
    [position]
  );
 
  // ============ Utility: bearingTo ============
  const bearingTo = useCallback(
    (latitude: number, longitude: number): number | null => {
      if (!position) {
        return null;
      }
 
      return calculateBearing(
        position.coords.latitude,
        position.coords.longitude,
        latitude,
        longitude
      );
    },
    [position]
  );
 
  // ============ Return ============
  return {
    position,
    loading,
    error,
    permission,
    isSupported,
    getCurrentPosition,
    watchPosition,
    clearWatch,
    distanceFrom,
    bearingTo,
  };
}