最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How geolocation.getCurrentPosition return value? - Stack Overflow

programmeradmin7浏览0评论

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)
    }

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)
    }
Share Improve this question edited Apr 15, 2019 at 6:57 Dale K 27.3k15 gold badges57 silver badges83 bronze badges asked Nov 29, 2017 at 3:27 heihei 1091 gold badge2 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 18

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 plete
    console.log(position);
}

main();

https://jsfiddle/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 plete
}

main();

https://jsfiddle/DerekL/90129LoL/

发布评论

评论列表(0)

  1. 暂无评论