0

我对编程很陌生,因为我上周才开始编程。代码部分 -

var office = document.getElementById('start').value;
var pickup = document.getElementById('start').value;
 $.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins="+office+"&destinations="+pickup+"&mode=drivinging&language=en&sensor=false",function(data){
alert(data['status']);

返回的数据 -

http://maps.googleapis.com/maps/api/distancematrix/json?origins=edingbourgh&destinations=london&mode=drivinging&language=en&sensor=false

我可以使用data['status']data.status访问和显示“ destination_addresses ”、“ status ”和“ origin_addresses ”,但无法访问rows[]中的任何内容我已经尝试了我可能知道的所有方法。

我以为我可以做 data.row.distance.text但什么也没发生。

任何帮助将非常感激

4

4 回答 4

2

rows is an array, as well as elements, you need to access it like this:

var text = data.rows[0].elements[0].distance.text;
// this yields "652 km"

You want to return the first element of the array, because it has only one. rows[] doesn't access anything. You need a number within the brackets. There might be multiple objects rows or elements. Fill in the array index you want:

var text = data.rows[2].elements[5].distance.text;
// this yields text from the sixth element of the third row.


Original response:

  {
     "destination_addresses" : [ "London, UK" ],
     "origin_addresses" : [ "Edinburgh, City of Edinburgh, UK" ],
     "rows" : [
        {
           "elements" : [
              {
                 "distance" : {
                    "text" : "652 km",
                    "value" : 652135
                 },
                 "duration" : {
                    "text" : "6 hours 44 mins",
                    "value" : 24247
                 },
                 "status" : "OK"
              }
           ]
        }
     ],
     "status" : "OK"
  }
于 2013-08-16T12:24:16.733 回答
1

try

alert(data['rows'][0].elements[0].distance.text);

output 625km

于 2013-08-16T12:24:28.390 回答
0

Include jquery and try to parse the json data returned using JSON.parse which would give you a javascript array object

var dataArray = JSON.parse(data['status']);
alert(dataArray['status']);

Hope this helps

于 2013-08-16T12:24:48.780 回答
0

首先将json解析成一个真实的对象:

try {
  var realObject = JSON.parse(jsonString);
} catch (err) {
  console.log("error parsing json string");
}

并且您应该能够通过以下方式访问:

var text = data.rows[0].elements[0].distance.text;
于 2013-08-16T12:31:48.643 回答