Last active
April 3, 2024 16:48
-
-
Save fjcerignoni/663337f7ccad917bcc12855ccfac028c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | |
| ]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment