Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically displays the local weather of the user using the navigator.geolocation feature.
Expected Outcome: When the user clicks 'block', the loadApp if-statement should execute and default to a predetermined coordinate (Kansas for now). If the user chooses 'allow', their latitude/longitude information is captured, enabling the initial API request for the user's local weather.
Actual Issue: When the user selects 'block', the code halts completely without progressing to the if-statement in loadApp. It seems stuck. However, clicking 'allow' works correctly, allowing me to obtain coordinates when testing on my personal device.
Previous Attempts: I have researched the problem online and attempted to create a function that checks the status of the global permission object. I tried seeking out any instances where permission was denied to potentially break out of it, but the status consistently remains 'prompted'. Additionally, I experimented with using the reject statement in my promise, but it only triggers when the user has zero geolocation capabilities.
function getLocationFromUser (){
//promisify the callback by wrapping it in a promise and return the promise immediately
//wrapping things in a promise is a way to return from a callback
return new Promise((resolve, reject) => {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
console.log(position.coords.latitude, position.coords.longitude);
let defaultCoords = [];
defaultCoords.push(position.coords.latitude);
defaultCoords.push(position.coords.longitude);
//this resolve statement is what is actually returned by the promise
resolve((defaultCoords));
});
} else {
reject(console.log('Geolocation not supported'));
}
});
}
async function loadApp(){
let defaultLocation = await getLocationFromUser();
if(!defaultLocation){
alert('user denied us');
//load a default city
getWeatherData(37.9795, 23.7162);
} else {
console.log(defaultLocation);
let lat = defaultLocation[0];
let lon = defaultLocation[1];
getWeatherData(lat, lon);
}
}
function getWeatherData(lat, lon){
//this is where my API call will run using the lat and lon data
}
loadApp().then(data => console.log(data)).catch(err => console.log(err));