I'm trying to get the users location using the geolocation api, in my success callback I want to return the getPosition function with the position value.
I've tried a few approaches but non of them have been successful so far, this is where I'm at right now.
function getPosition() {
// If geolocation is available, try to get the visitor's position
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
console.log("Getting the position information...")
} else {
alert("Sorry, your browser does not support HTML5 geolocation.");
}
function successCallback(position) {
return position
}
function errorCallback(error) {
alert("Sorry, we can't retrieve your local weather without location permission.");
}
};
const getLocalWeather = async () => {
if(loading === 'loading') return
setLoading('loading')
console.log(getPosition())
// this console log should return the position from getPosition
setLoading('done')
};
The getPosition function itself works fine but I'm not able to access it's return value in the getLocalWeather function.
Any help would be appreciated, I've been stuck on this for a while.
CodePudding user response:
You're already familiar with async/await by the looks of things so wrap your getPosition
code in a promise, and then await
the response in getLocalWeather
.
This code may not work in the snippet, but I've tested it locally and it logs the position without any problems.
function getPosition() {
return new Promise((res, rej) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
console.log("Sorry, your browser does not support HTML5 geolocation.");
}
function success(position) {
res(position)
}
function error(error) {
console.log("Sorry, we can\'t retrieve your local weather without location permission.");
}
});
};
async function getLocalWeather() {
console.log(await getPosition())
};
getLocalWeather();