gpt4 book ai didi

javascript - geolocation.getCurrentPosition 如何返回值?

转载 作者:行者123 更新时间:2023-11-30 09:29:02 24 4
gpt4 key购买 nike

我正在使用 getCurrentPosition 获取本地纬度和经度。我知道这个函数是异步的,只是想知道如何返回可以被其他函数访问的纬度和经度值?

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

最佳答案

我建议你把它包装在一个 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 版本:

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/

关于javascript - geolocation.getCurrentPosition 如何返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com