首页 > 解决方案 > 来自谷歌地图 api url fetch 的空 json

问题描述

我正在使用谷歌地图 API 从坐标中获取城市名称。当我获取 API url 时,我得到一个空的 json

unction callWCoords(position) {
    let latitude = position.coords.latitude;
    let longitude =position.coords.longitude;
    let call1;
    let API1="https://maps.googleapis.com/maps/api/geocode/json?latlng=+"+latitude+","+longitude+"&key=AIzaSyAfH3Ypu0Al8HpNRXhOPEzGLeNbkxOlsoI"
    fetch(API1).then(
        response=>{alert(JSON.stringify(response));

        }).then( data=>{

    })
    //getPlaceC(call1);

}

JSON.stringfy(response)"{}"如果我JSON.stringfy(data)在第二个 .then 块中尝试,也会返回。因为在官方的 google json 中,我应该得到一个名为results我试图替换的数组resultsdata但它没有用。

标签: javascriptjsonapi

解决方案


function callWCoords(position) {
    let latitude = position.coords.latitude;
    let longitude =position.coords.longitude;
    let API1="https://maps.googleapis.com/maps/api/geocode/json?latlng=+"+latitude+","+longitude+"&key=AIzaSyAfH3Ypu0Al8HpNRXhOPEzGLeNbkxOlsoI"
    fetch(API1).then(res => res.json()).then(data => console.log(data))
}

您必须在 fetch 返回时调用 res.json() 函数来获取数据。此外,您不会在警报后返回数据,这基本上是从下一个删除数据.then


推荐阅读