无法读取未定义的 属性 'geometry'

Cannot read property 'geometry' of undefined

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

  _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 已经定义了一些日志记录,所以我不明白为什么我仍然会收到错误。提前谢谢你。

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