【问题标题】:Cannot read property无法读取属性
【发布时间】:2014-10-17 03:17:00
【问题描述】:

这是我的脚本:

            if(entfernung2<=1 && drive=="AUT"){
                dauer = new google.maps.DistanceMatrixService();
                dauer.getDistanceMatrix({
                origins: ["48.142362,11.549859"],
                destinations: ["48.2,11.4"],
                travelMode: google.maps.TravelMode.WALKING,
                unitSystem: google.maps.UnitSystem.METRIC,
                })
            dauer1=dauer.rows.elements.duration.text;
            };

如果我记录 dauer1 会显示以下错误:

未捕获的类型错误:无法读取未定义的属性“元素” 未捕获的类型错误:无法读取未定义的属性“应用”

怎么了? :/

编辑:

            if(entfernung2<=1 && drive=="AUT"){
                dauer = new google.maps.DistanceMatrixService();
            dauer.getDistanceMatrix(
            {
              origins: ["48.142362,11.549859"],
              destinations: ['"'+data.position.latitude+','+data.position.longitude+'"'],
              travelMode: google.maps.TravelMode.WALKING,
              unitSystem: google.maps.UnitSystem.METRIC
            }, setDauer1);

            function setDauer1(response, status) {
              dauer1 = response.rows[0].elements[0].duration.value;
              console.log(dauer1);
            }};

【问题讨论】:

  • dauer.rows 是一个数组,它没有 elements 属性。但是数组的对象可以(例如dauer.rows[0].elements.duration.text
  • 现在我得到错误 Uncaught TypeError: Cannot read property '0' of undefined
  • Json 看起来像这样: { "destination_addresses" : [ "San Francisco, Californie, États-Unis" ], "origin_addresses" : [ "Vancouver, BC, Canada" ], "rows" : [ {“元素”:[{“距离”:{“文本”:“1 709公里”,“价值”:1709199},“持续时间”:{“文本”:“3 jours 19 heures”,“价值”: 327594 },“状态”:“确定”}] }],“状态”:“确定”}

标签: javascript jquery google-maps


【解决方案1】:

getDistanceMatrix 是异步的,所以dauer1 是在dauer 更新之前定义的。通过查看docs,需要回调:

dauer.getDistanceMatrix(
{
  origins: ["48.142362,11.549859"],
  destinations: ["48.2,11.4"],
  travelMode: google.maps.TravelMode.WALKING,
  unitSystem: google.maps.UnitSystem.METRIC
}, setDauer1);

function setDauer1(response, status) {
  dauer1 = response.rows[0].elements[0].duration.text;
  // your code continues here
}

【讨论】:

  • 谢谢 :) ... 现在我得到错误 Uncaught TypeError: Cannot read property 'rows' of undefined and有时 Uncaught TypeError: Cannot read property '0' of null
  • if(entfernung2
  • @SebastianLzlem 我刚刚更新了那行。 elements 也是一个数组,所以如果你想要第一个元素,添加[0]。请注意,这段代码不会检查是否真的有结果。
  • @SebastianLzlem 为我工作:JS Fiddle Demo。使用console.log(dauer1) 而不是alert,您会在控制台中得到什么 (F12)?
  • 所以最后它得到了这个代码(上面编辑)..我得到错误未捕获类型错误:无法读取未定义的属性'值'
猜你喜欢
  • 2011-01-07
  • 2022-01-22
  • 2018-05-13
  • 2015-03-29
  • 2018-07-04
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多