Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

javascript - How geolocation.getCurrentPosition return value?

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)
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...