0.2.5 • Published 4 years ago

@snappmarket/use-geolocation v0.2.5

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

useGeoLocation

🗺 easily deal with navigator location API

version downloads PRs Welcome MIT License

Watch on GitHub Star on GitHub

get started

We provide two way of using this package single or multi :

npm i @snappmarket/use-geolocation
OR
npm i @snappmarket/hooks

usage

import useGeoLocation from '@snappmarket/use-geolocation';
// or 
// import { useGeoLocation } from '@snappmarket/hooks';


const MyComponenet = props => {
  const [position, error] = useGeoLocation(LOCATION_ACCESS_TIMEOUT || 5000);
};

source code

import { useEffect, useState } from 'react';

/**
 * Get access to geo location based on timeout
 * @note : if timeout error it will send TIMEOUT as error
 * @param timeout number
 * @param options object for getCurrentPosition options
 * @returns {[*, *]}
 */
const useGeoLocation = (timeout, options) => {
  let timeoutHandler;
  let canceled = false;

  const [position, setPosition] = useState();
  const [error, setError] = useState();

  useEffect(() => {
    /**
     * Handle timeout clear
     */
    const timeoutCanceler = () => {
      clearTimeout(timeoutHandler);
    };

    /**
     * Success getting geolocation
     * @param pos
     */
    const successGetLocation = pos => {
      if (!canceled) {
        setPosition(pos);
      }
      timeoutCanceler();
    };

    /**
     * Failure getting geolocation
     * @param err
     */
    const failGetLocation = err => {
      if (!canceled) {
        setError(err);
      }
      timeoutCanceler();
    };

    timeoutHandler = setTimeout(() => {
      setError('TIMEOUT');
    }, timeout);

    /**
     * Get geolocation access of navigator
     */
    navigator.geolocation.getCurrentPosition(
      successGetLocation,
      failGetLocation,
      options
    );

    return () => {
      canceled = true;
    };
  }, [options]);

  return [position, error];
};

export default useGeoLocation;
0.2.5

4 years ago

0.2.3

4 years ago

0.2.1-alpha.0

4 years ago

0.1.25

4 years ago

0.1.23

4 years ago

0.1.22

4 years ago

0.1.21

4 years ago

0.1.11

4 years ago

0.1.12

4 years ago

0.1.14

4 years ago

0.1.7

4 years ago

0.1.6

4 years ago

0.1.5

4 years ago