await for getCurrentPosition() is not working

Viewed 1315

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.

1 Answers

The main problem you've got is getLongAndLat() is not set up to work with await. It returns an implicit promise (caused by the async prefix) but not one that's resolved only when the location has been granted (or denied). Since getCurrentPosition() doesn't return a promise, we'll need to handle the promise manually, ourselves.

Try this:

locate.addEventListener("click", locateButtonFetch);

function getLongAndLat() {
    return new Promise((resolve, reject) =>
        navigator.geolocation.getCurrentPosition(resolve, reject)
    );
}

const locateButtonFetch = async () => {
    try {
        let position = await getLongAndLat(),
            { coords } = position,
            url = "https://api.openweathermap.org/data/2.5/onecall?lat="+coords.latitude+"&lon="+coords.longitude+"&exclude=daily&appid={myOWApi key}&units=metric";
        await fetch(url)
            .then(resp => resp.json())
            .then(data => {
                let future = data;
                console.log(future);
            })
            .catch(e => console.log(error));
    } catch(e) {
        alert('Error: '+e.message);
    }
}
Related