首页 > 解决方案 > 调用 google API json 文件并将其显示为 html,未检索到数据但成功调用站点

问题描述

$.ajax({
    type: "GET",
    url: 'https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=I-Removed-My-Api-For-Posting',
	dataType: "json",
  success: function(data) {
  console.log('success',data);
    drawTable(data);
    }
});

function drawTable(data) {
   for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }

}

function drawRow(rowData) {
   var row = $("<tr />")
    $("#personDataTable").append(row); 
    row.append($("<td>" + rowData.routes.bounds.northeast.lat + "</td>"));
	
	
}
table {
  border: 2px solid #666;   
    width: 100%;
}
th {
  background: #f8f8f8; 
  font-weight: bold;    
    padding: 2px;
}	
<!DOCTYPE html>
<html>
  <head>
    <title>Json to HTML</title>
	  <meta charset="utf-8">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script type="text/javascript" src="js/table.js"></script>
	    <link rel="stylesheet" href="css/table.css">
		 
  </head>
<body>

<table id="personDataTable">


    <tr>
        <th>Lat</th>       
    </tr>
</table>

 
</body>
</html>

    {
   "geocoded_waypoints" : [
  {
     "geocoder_status" : "OK",
     "place_id" : "ChIJa147K9HX3IAR-lwiGIQv9i4",
     "types" : [ "amusement_park", "establishment", "point_of_interest" ]
  },
  {
     "geocoder_status" : "OK",
     "place_id" : "ChIJzzgyJU--woARcZqceSdQ3dM",
     "types" : [ "amusement_park", "establishment", "point_of_interest" ]
  }
   ],
   "routes" : [
  {
     "bounds" : {
        "northeast" : {
           "lat" : 34.1373841,
           "lng" : -117.9220826
        },
        "southwest" : {
           "lat" : 33.8151707,
           "lng" : -118.3575585
        }
     },

没有 CORS 问题,并且在使用自己的 API 密钥编辑 URL 后,我已成功调用该网站。对于控制台日志,我收到了 success {geocoded_waypoints: Array(2), routes: Array(1), status: "OK"} ,请问有什么方法可以让我从 json 代码中检索 lat 和 lng 吗?我一直在尝试不同的方法,但它们都不适合我。我的代码有什么问题?感谢您的帮助。

标签: javascriptjson

解决方案


您的代码是错误rowData.routes的,因为array. rowData.routes[0].bounds.northeast.lat您可以通过或在路线上创建循环来获取第一条路线。

rowData.routes.forEach(function(route) {
    row.append($("<td>" + route.bounds.northeast.lat + "</td>"));
}

推荐阅读