Skip to content

Instantly share code, notes, and snippets.

@fjcerignoni
Last active April 3, 2024 16:48
Show Gist options
  • Save fjcerignoni/663337f7ccad917bcc12855ccfac028c to your computer and use it in GitHub Desktop.
Save fjcerignoni/663337f7ccad917bcc12855ccfac028c to your computer and use it in GitHub Desktop.

Revisions

  1. fjcerignoni revised this gist Dec 14, 2022. No changes.
  2. fjcerignoni created this gist Dec 5, 2020.
    48 changes: 48 additions & 0 deletions useGeoLocation.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    import React from 'react';

    // constraints_sample = {
    // enableHighAccuracy: true,
    // timeout: 5000,
    // maximumAge: 0,
    // };

    export function useGeoLocation(constraints) {
    const [location, setLocation] = React.useState(null);
    const [accuracy, setAccuracy] = React.useState(null);
    const [loading, setLoading] = React.useState(false);
    const [error, setError] = React.useState(false);

    const success = ({ coords: { latitude, longitude, accuracy } }) => {
    setLoading(false);
    setLocation([latitude, longitude]);
    setAccuracy(accuracy);
    };

    const err = (err) => {
    setLoading(false);
    setError(err);
    };

    function requestGeoLocation() {
    if (navigator.geolocation) {
    setLoading(true);
    navigator.geolocation.getCurrentPosition(success, err, constraints);
    } else {
    setError(true);
    }
    }

    function cleanGeoLocation() {
    setLocation(null);
    setAccuracy(null);
    }

    return [
    location,
    accuracy,
    loading,
    error,
    requestGeoLocation,
    cleanGeoLocation,
    ];
    }