各位!
我正在尝试使用 Google Maps API 获取某个位置的纬度或经度。但我不知道如何使用 Fetch API 及其 promise 返回值。
我可以记录纬度和经度:
let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=london'
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data.results[0].geometry.location.lat)
console.log(data.results[0].geometry.location.lng)
})
输出:
51.5073509
0.1277583
但我想将这段代码封装在一个函数中:
function getLatitudeOrLongitude(url, LatitudeOrLongitude) {
fetch(url)
.then(response => response.json())
.then(data => {
if (LatitudeOrLongitude === 'latitude')
return data.results[0].geometry.location.lat
else
return data.results[0].geometry.location.lng
})
}
let latitudeOfLondon = getLatitudeOrLongitude(url, 'latitude')
console.log(latitudeOfLondon)
输出:
undefined
有人可以指出我出了什么问题吗?谢谢大家!
编辑:Here你可以找到一个带有代码的JS Bin
最佳答案
您必须使用 .then
来处理 Promise 的结果:
function getLatitudeOrLongitude(url, LatitudeOrLongitude) {
return fetch(url)
.then(response => response.json())
.then(data => {
if (LatitudeOrLongitude === 'latitude')
return data.results[0].geometry.location.lat
else
return data.results[0].geometry.location.lng
})
}
getLatitudeOrLongitude(url, 'latitude')
.then((latitudeOfLondon) => console.log(latitudeOfLondon));
关于javascript - 如何将 Fetch API 的值传递给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40119346/