6

I am using getCurrentPosition to get local latitude and longitude. I know this function is asynchronous, just wondering how to return latitude and longitude value that can be accessed by other functions?

    function getGeo() {
        navigator.geolocation.getCurrentPosition(getCurrentLoc)
    }

    function getCurrentLoc(data) {
        var lat,lon;
        lat=data.coords.latitude;
        lon=data.coords.longitude;
        getLocalWeather(lat,lon)
        initMap(lat,lon)
    }
Dale K
  • 25,246
  • 15
  • 42
  • 71
hei
  • 109
  • 1
  • 2
  • 10

1 Answers1

17

I would suggest you wrapping it in a promise:

function getPosition() {
    // Simple wrapper
    return new Promise((res, rej) => {
        navigator.geolocation.getCurrentPosition(res, rej);
    });
}

async function main() {
    var position = await getPosition();  // wait for getPosition to complete
    console.log(position);
}

main();

https://jsfiddle.net/DerekL/zr8L57sL/

ES6 version:

function getPosition() {
    // Simple wrapper
    return new Promise((res, rej) => {
        navigator.geolocation.getCurrentPosition(res, rej);
    });
}

function main() {
    getPosition().then(console.log); // wait for getPosition to complete
}

main();

https://jsfiddle.net/DerekL/90129LoL/

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • simple and clean! Thank you!! – Ricardinho Mar 13 '20 at 03:02
  • Excellent indeed! The 'return new Promise' method is a great way to work with callbacks within a function (in this case geolocation.getCurrentPosition) where normal .then handling falls short – beyondtdr Jan 08 '21 at 14:01