I'm writing click event on button to get localisation using navigator.geolocation.getCurrentPosition() to later fetch from openweathermap.org using longitude and latitude I have just got.
My problem is, I cannot find the way for my code to wait to recieve coordinates, and then make a fetch, which leads to errors because link to fetch from is invalid. I know I should make a function await, but I have completly no clue how to make that.
locate.addEventListener("click", function () {
locateButtonFetch();
})
async function getLongAndLat() {
//i have tried to make that await for onSuccess result, but I don't know how
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
var onSuccess = async function (position) {
//that array is ofc global
localisationCords[0] = position.coords.latitude;
localisationCords[1] = position.coords.longitude;
};
function onError(error) {
alert('Error: ' + error.message);
}
const locateButtonFetch = async () => {
await getLongAndLat();
console.log(localisationCords[0] + " + " + localisationCords[1]); //this logs undefined + undefined
link = "https://api.openweathermap.org/data/2.5/onecall?lat=" + localisationCords[0] + "&lon=" + localisationCords[1] + "&exclude=daily&appid={myOWApi key}&units=metric";
await fetch(link)
.then((resp) => resp.json())
.then(function (data) {
future = data;
console.log(future);
})
.catch(function (error) {
console.log(error);
});
}
I'm definitly missing something, but all the posts on this forum I have found havent solved my problem, nor my tries to modify these.
Thanks in advance.