Files
nahodka-front/src/hooks/useGeolocation.js
2026-09-03 00:29:19 +03:00

132 lines
4.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useCallback, useEffect, useRef, useState } from "react";
export const GEO_STATUS = {
IDLE: "idle",
LOADING: "loading",
SUCCESS: "success",
DENIED: "denied",
UNSUPPORTED: "unsupported",
TIMEOUT: "timeout",
};
const DEFAULT_TIMEOUT = 10000;
/**
* Определяет код ошибки геолокации в понятный статус.
* @param {string|number} code — код из GeolocationPositionError
*/
function codeToStatus(code) {
switch (code) {
case 1: // PERMISSION_DENIED
return GEO_STATUS.DENIED;
case 2: // POSITION_UNAVAILABLE
return GEO_STATUS.UNSUPPORTED;
case 3: // TIMEOUT
return GEO_STATUS.TIMEOUT;
default:
return GEO_STATUS.UNSUPPORTED;
}
}
/**
* useGeolocation — переиспользуемый хук для запроса геолокации браузера.
*
* Возвращает:
* - coords { latitude, longitude, accuracy } | null
* - error текст ошибки (для логирования/диагностики) | null
* - status GEO_STATUS.* (loading / success / denied / unsupported / timeout)
* - requestLocation () => void — запустить запрос заново
*
* @param {Object} [options]
* @param {boolean} [options.onMount] запросить геолокацию сразу при монтировании
* @param {boolean} [options.enableHighAccuracy] точный режим (по умолчанию true)
* @param {number} [options.timeout] таймаут в мс (по умолчанию 10000)
*/
export function useGeolocation({
onMount = false,
enableHighAccuracy = true,
timeout = DEFAULT_TIMEOUT,
} = {}) {
const [coords, setCoords] = useState(null);
const [error, setError] = useState(null);
const [status, setStatus] = useState(GEO_STATUS.IDLE);
const timeoutRef = useRef(null);
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
};
}, []);
const requestLocation = useCallback(() => {
// Либо API полностью отсутствует, либо у геолокации нет getCurrentPosition.
if (!("geolocation" in navigator) || !navigator.geolocation) {
setCoords(null);
setError("Geolocation is not supported by this browser");
setStatus(GEO_STATUS.UNSUPPORTED);
return;
}
setStatus(GEO_STATUS.LOADING);
setError(null);
// Страховочный таймер: некоторые браузеры (Safari/WebKit) могут
// «зависать» в pending без вызова колбэков — не держим пользователя.
if (timeoutRef.current) clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
if (!mountedRef.current) return;
setCoords(null);
setError("Geolocation request timed out");
setStatus(GEO_STATUS.TIMEOUT);
}, timeout);
const finish = (resolvedCoords) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
if (!mountedRef.current) return;
setCoords({
latitude: resolvedCoords.latitude,
longitude: resolvedCoords.longitude,
accuracy: resolvedCoords.accuracy ?? null,
});
setError(null);
setStatus(GEO_STATUS.SUCCESS);
};
const fail = (err) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
if (!mountedRef.current) return;
setCoords(null);
setError(err && err.message ? err.message : "Geolocation failed");
setStatus(codeToStatus(err && err.code));
};
navigator.geolocation.getCurrentPosition(
(pos) => finish(pos.coords),
fail,
{ enableHighAccuracy, timeout, maximumAge: 60000 }
);
}, [enableHighAccuracy, timeout]);
useEffect(() => {
if (onMount) requestLocation();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { coords, error, status, requestLocation };
}