'Can not put geolocation inside variable [duplicate]
I'm trying to put my geolocation inside a variable to use in multiple places throughout my code. I've tried a couple ways of doing this but can't find one that works. Here is what I am currently trying but it always returns undefined. Does anyone know how to do this?
const getLocation = () => {
let position;
navigator.geolocation.getCurrentPosition(location => {
position = location;
});
return position;
};
Well I figured out how to make this work but it's currently flagged as a repeat post for another post that has nothing to do with this. What worked for me was passing the position as an argument into another function.
const init = () => {
navigator.geolocation.getCurrentPosition(function(position) {
loader.load().then(() => {
initMap(position);
});
});
};
The loader.load is for the google maps api.
Solution 1:[1]
I would clean up your code to use a Promise. Also should use the error callback... https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#examples
const getLocation = async () => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
resolve,
(err) => {
console.warn(`ERROR(${err.code}): ${err.message}`);
resolve(undefined)}, // might want to reject depending on error
{}, // options
);
});
};
const location = await getLocation();
if (location) // do something
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jpoehnelt |
