JSFiddle - React, Tailwind, and code Playground
by Russ Bain
HTML
<p>
Note: to get the Geolocation API to work,
you may need to enable it in Chrome devTools.
Open the console, hit the 'esc' key, click on the the three dot menu,
choose 'sensors', then choose a location from the
drop down menu
</p>
JavaScript
/**
* Wrap function in a Promise.
* Resolve when position is found.
* Reject when error occurs.
*/
var foo;
const getLocation = () => new Promise(
(resolve, reject) => {
window.navigator.geolocation.getCurrentPosition(
position => {
const location = {
lat:position.coords.latitude,
long:position.coords.longitude
};
resolve(location); // Resolve with location. location can now be accessed in the .then method.
},
err => reject(err) // Reject with err. err can now be accessed in the .catch method.
);
}
);
/**
* then is called when the Promise is resolved
* catch is called when the Promise rejects or encounters an error.
*/
getLocation()
.then((location) => {foo = location})
.catch(error => console.log(error));
console.log('OUTSIDE', foo);