How geolocation.getCurrentPosition return value?(geolocation.getCurrentPosition 如何返回值?)
问题描述
我正在使用 getCurrentPosition 来获取当地的纬度和经度.我知道这个函数是异步的,只是想知道如何返回其他函数可以访问的经纬度值?
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 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 版本:
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/
这篇关于geolocation.getCurrentPosition 如何返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:geolocation.getCurrentPosition 如何返回值?


- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01