@rooks/use-geolocation
Version:
A hook to provide the geolocation info on client side.
81 lines (77 loc) • 2.77 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('tslib'), require('react')) :
typeof define === 'function' && define.amd ? define(['tslib', 'react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.useGeolocation = factory(global.tslib, global.React));
}(this, (function (tslib, react) { 'use strict';
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] = react.useState(null);
const { when, enableHighAccuracy, timeout, maximumAge } = geoLocationOptions;
react.useEffect(() => {
function getGeoCode() {
return tslib.__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;
}
return useGeolocation;
})));
//# sourceMappingURL=index.js.map