Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
81 lines (61 sloc) 2.48 KB

useGeolocationState

Returns an object containing the position information, the isSupported boolean flag reporting whether the geolocation API is supported or not and the isRetrieving boolean flag reporting whether the hook is fetching the current position or not.

The position is retrieved by using the Geolocation API, when supported.

It possibly accepts an object of geolocation options to be used as parameter when using the Geolocation.getCurrentPosition() method.

Why? πŸ’‘

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

Basic Usage:

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

const PositionReporter = () => {
  const {isSupported, isRetrieving, position } = useGeolocationState(); 
  
  return (
   <DisplayDemo>
     The current position is:
     {isRetrieving && (<p>Retrieving position...</p>)}
     {isSupported && position && [
       <p key={0}>Lat: {position.coords.latitude}</p>,
       <p key={1}>Lng: {position.coords.longitude}</p>
     ]}
   </DisplayDemo>
  );
};

<PositionReporter />

Options:

Before using, please read about the geolocation options

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

const PositionReporter = () => {
  const {isSupported, isRetrieving, position } = useGeolocationState({ 
    enableHighAccuracy: true, 
    timeout: 0xFFFFFFFF,
    maximumAge: 0,
  }); 
  
  return (
   <DisplayDemo>
     The current high accuracy position is:
     {isRetrieving && (<p>Retrieving position...</p>)}
     {isSupported && position && [
       <p key={0}>Lat: {position.coords.latitude}</p>,
       <p key={1}>Lng: {position.coords.longitude}</p>
     ]}
   </DisplayDemo>
  );
};

<PositionReporter />

Mastering the hook

βœ… When to use

  • If in need to easily access the Geolocation API
  • If in need to abstract some geolocation related logic into a custom hooks

πŸ›‘ 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.