【问题标题】:Cannot read property 'geometry' of undefined无法读取未定义的属性“几何”
【发布时间】:2017-10-15 06:03:30
【问题描述】:

我的代码运行正常,但是每当调用此函数时,我都会在移动设备上收到与此问题标题相同名称的错误。

  _matchAddresses(id) {
   fetch('https://myapp.com/rest/jobs/address/' + id)
   .then((response) => response.json())
   .then((responseJson) => {
     var addresses = [];
     console.log('addresses: ' + responseJson);
     for (var i=0; i<responseJson.length; i++) {
       addresses.push(responseJson[i]);
       for (var j=0; j<addresses.length; j++) {
         fetch('https://maps.googleapis.com/maps/api/geocode/json?address='+ addresses[j].split(" ") + '&key=googleapikey')
         .then((response) => response.json())
         .then((responseJson) => {
           let lat = responseJson.results["0"].geometry.location.lat; //error here
           let lng = responseJson.results["0"].geometry.location.lng; //error here
           console.log("coordinates: " + lat + " " + lng); //returns coordinates every time

           if (this._latMatch(userLat, lat) && this._lngMatch(userLng, lng)) {
               this._myFunction();
               console.log("fire");
           }

         })
         .catch((error) => {
           console.error(error);
         });
     }
   }
 });
}

我知道 lat 和 lng 已经定义了一些日志记录,所以我不明白为什么我仍然会收到错误。提前谢谢你。

【问题讨论】:

    标签: json react-native fetch


    【解决方案1】:

    您的results["0"] 是空的,这就是您收到该错误的原因。由于您在 for 循环上进行迭代并且您成功打印出坐标,因此我猜测至少其中一个对 Google API 的提取没有返回预期结果。要对此进行测试,您可以在尝试访问它之前记录结果对象并检查错误之前返回的对象。

    【讨论】:

    • 感谢您的帮助。事实证明,我后端的一个地址中有一个错字,这导致 googlemaps api 搜索一个不存在的地址。有趣的是,我是如何获得正确数量的不同坐标的……如果我有足够的声誉,我会给你投赞成票。
    • 很高兴能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2020-10-30
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多