UNPKG

geolocator-helper

Version:

Lightweight geolocation library providing latitude, longitude, address conversion via OlaMaps API, and real-time network status detection.

92 lines (79 loc) 2.85 kB
import { useState, useEffect } from 'react'; const convertToAddress = async (lat, lng, apiKey) => { try { const url = `https://api.olamaps.io/places/v1/reverse-geocode?latlng=${lat},${lng}&api_key=${apiKey}`; const response = await fetch(url); const data = await response.json(); // console.log(data) if (data.status === 'ok') { return data?.results[0]?.formatted_address; } else { throw new Error(data?.message) } } catch (error) { // console.log(error); throw new Error(error.message) } }; const getLocation = async (apiKey) => { let address, latitude, longitude, error; try { const { coords } = await new Promise((resolve, reject) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(resolve, reject); } else { reject(new Error("Geolocation is not supported by your browser. Allow access to location.")); } }); latitude = coords.latitude; longitude = coords.longitude; if(apiKey){ address = await convertToAddress(coords.latitude, coords.longitude, apiKey); } // console.log(coords.latitude, coords.longitude, null, address); //console.log("inside try", latitude, longitude, address, error); } catch (err) { // console.log("inside catch errrrr|||||", err); error = err.message || "Failed to get location."; address = null; // console.log("inside catch", latitude, longitude, address, error); } finally { //console.log("inside finally", latitude, longitude, address, error); return { latitude, longitude, address, error } } }; const useNetworkStatus=()=>{ const [isOnline, setIsOnline] = useState(navigator.onLine); useEffect(()=>{ const handleOnline = () => setIsOnline(true); const handleOffline = () => setIsOnline(false); window.addEventListener('online', handleOnline); window.addEventListener('offline', handleOffline); return () => { window.removeEventListener('online', handleOnline); window.removeEventListener('offline', handleOffline); }; },[]); return isOnline; }; const useGeolocation = (apiKey) => { const [location, setLocation] = useState({ latitude: null, longitude: null, address: null, error: null, }); useEffect(() => { const fetchLocation = async () => { const locationData = await getLocation(apiKey); setLocation(locationData); }; fetchLocation(); }, [apiKey]); return location; }; export { useGeolocation, useNetworkStatus };