UNPKG

@rooks/use-geolocation

Version:

A hook to provide the geolocation info on client side.

76 lines (73 loc) 2.27 kB
import { __awaiter } from 'tslib'; import { useState, useEffect } from 'react'; function getGeoLocation(options) { return new Promise((resolve, reject) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(res => { const { coords } = res; const { latitude, longitude } = coords; resolve({ lat: latitude, lng: longitude, isError: false, message: "" }); }, err => { reject({ message: err.message, isError: true }); }, options); } else { reject({ isError: true, message: "Geolocation is not supported for this Browser/OS." }); } }); } // interface IUseGeoLocationHook { // when?: boolean; // } // const defaultHookOptions = { // when: true // }; const defaultGeoLocationOptions = { enableHighAccuracy: false, timeout: Infinity, maximumAge: 0, when: true }; /** * useGeolocation * Gets the geolocation data as a hook * @param geoLocationOptions Geolocation options */ function useGeolocation( // hooksOptions: IUseGeoLocationHook = defaultHookOptions, geoLocationOptions = defaultGeoLocationOptions) { const [geoObj, setGeoObj] = useState(null); const { when, enableHighAccuracy, timeout, maximumAge } = geoLocationOptions; useEffect(() => { function getGeoCode() { return __awaiter(this, void 0, void 0, function* () { try { const value = yield getGeoLocation({ when, enableHighAccuracy, timeout, maximumAge }); setGeoObj(value); } catch (e) { setGeoObj(e); } }); } if (when) { getGeoCode(); } }, [when, enableHighAccuracy, timeout, maximumAge]); return geoObj; } export default useGeolocation; //# sourceMappingURL=index.esm.js.map