A new challenge I'm facing involves creating a vanilla JavaScript weather app. I want the app to request the user's location with their permission and use it in a fetch call as a template string, which will then determine their location and display the temperature.
However, I've encountered an issue where the fetch call is executed before the user has a chance to click the button that allows their location to be accessed.
Is there a way to delay the fetch call until after the function runs? Can I incorporate the fetch call into the onclick event attached to the function?
var latitude, longitude;
function allow() {
navigator.geolocation.getCurrentPosition(currentPosition);
};
function currentPosition(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
};
function onPositionReady() {
console.log(latitude, longitude);
// proceed
};
let api = {
key: '456fa9bb93098fb3454b25380512d491',
};
fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
.then(response => response.json())
.then(data => {
// Here's a list of repos!
console.log(data)
});