【发布时间】:2018-10-25 02:42:32
【问题描述】:
我开发了一小段代码,它可以获取当前的纬度和经度,并将它们传递给 Google 地图 URL 以获取地图数据。
lat 和 lon 变量最初设置为 undefined,然后在调用 navigator.geolocation.getCurrentPosition 时更新它们的值。此函数确实通过位置对象正确返回数据。但是不知何故,变量的值没有更新,并且在传递到 URL 时仍然未定义。
问题出在哪里?
const getLocationDetails = async () => {
let lat = undefined;
let lon = undefined;
await navigator.geolocation.getCurrentPosition( position => {
lat = position.coords.latitude;
lon = position.coords.longitude;
});
const res = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}`,
{ method: 'GET' });
const response = await res.json();
};
【问题讨论】:
-
position.coords.latitude这是已经存在还是需要一些时间才能填充?只需创建一个新的异步函数,它将返回值。并在定义let lat = asynfunction();时使用它