javascript - 调用 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 吗?我一直在尝试不同的方法,但它们都不适合我。我的代码有什么问题?感谢您的帮助。
解决方案
您的代码是错误rowData.routes
的,因为array
. rowData.routes[0].bounds.northeast.lat
您可以通过或在路线上创建循环来获取第一条路线。
rowData.routes.forEach(function(route) {
row.append($("<td>" + route.bounds.northeast.lat + "</td>"));
}
推荐阅读
- python - python中的倒置标准最小二乘回归(ISR)
- python-3.x - 使用 Google-Slide-API 和 python 更改表格列宽
- chatbot - 我们可以通过托管在 azure 上的 ChatBot 应用程序调用客户端机器的 exe 来访问聊天机器人是 MS Teams
- python - For循环“TypeError:字符串索引必须是整数” - 嵌套python字典
- php - 使用数据库驱动程序在 Laravel 队列中获取作业 ID
- microsoft-dynamics - 无法从 NavJsonValue 转换为 NavDate
- discord.py - x秒后如何在discord.py中删除用户编写的命令
- c++ - 对 2 个父母方法的模棱两可的调用
- jmeter - Read id one by one in tear down and get the status
- azure - 无法从 Azure Active Directory 中删除受邀用户