Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
@antonioru antonioru useDrag ac5a719 Jan 13, 2020
1 contributor

Users who have contributed to this file

85 lines (62 sloc) 2.27 KB

useGeolocation

Returns an array where the first item is the geolocation state from useGeolocationState and the second one is an object of handler setters from the useGeolocationEvents.

It is intended as a shortcut to those hooks.

Why? πŸ’‘

  • allow to easily access the Geolocation API
  • takes care of adding the geolocation events listeners
  • takes care of cleaning the listener when the component will unmount
  • allow to perform abstractions on geolocation related events

Basic Usage:

import { useGeolocation } from 'beautiful-react-hooks'; 

const PositionReporter = () => {
  const [geoState, { onChange }] = useGeolocation(); 
  
  onChange(() => {
    console.log('Position changed...');
  });
    
  return (
   <DisplayDemo>
     The current position is:
     {geoState.isRetrieving && (<p>Retrieving position...</p>)}
     {geoState.isSupported && geoState.position && [
       <p key={0}>Lat: {geoState.position.coords.latitude}</p>,
       <p key={1}>Lng: {geoState.position.coords.longitude}</p>
     ]}
   </DisplayDemo>
  );
};

<PositionReporter />

Options:

Before using, please read about the geolocation options

import { useGeolocation } from 'beautiful-react-hooks'; 

const PositionReporter = () => {
  const [geoState, { onChange }] = useGeolocation({ 
    enableHighAccuracy: true, 
    timeout: 0xFFFFFFFF,
    maximumAge: 0,
  }); 
  
  onChange(() => {
    console.log('Position changed...');
  });
  
  return (
   <DisplayDemo>
     The current position is:
     {geoState.isRetrieving && (<p>Retrieving position...</p>)}
     {geoState.isSupported && geoState.position && [
       <p key={0}>Lat: {geoState.position.coords.latitude}</p>,
       <p key={1}>Lng: {geoState.position.coords.longitude}</p>
     ]}
   </DisplayDemo>
  );
};

<PositionReporter />

Mastering the hook

βœ… When to use

  • If in need to easily access the Geolocation API.

πŸ›‘ What not to do

  • Don't use this hook to try to guess the user's device capabilities
  • Don't access the geolocation state before checking hte isSupported flag
You can’t perform that action at this time.