我对 Javascript 不是很流利,但我正在尝试使用它构建一个简单的 Web 应用程序以尝试学习更多知识。
我想使用 Google Distance Matrix API 来查询两个地址之间的距离。
我有两个输入字段,它们使用 Google 的自动完成功能来获取地址,然后我使用地址的 place_id
向 API 进行查询。
我认为我需要使用 JSONP 来调用 API 并获取数据,但我在使用响应时遇到了问题,并且在我的控制台中收到以下错误:
Uncaught SyntaxError: Unexpected token :
我一直在四处寻找,每个人都在结合使用 PHP 和 JSONP - 但是我想避免这种情况,并将整个过程保留在客户端。
如何发出请求,然后使用返回的 JSON 响应?
这是我目前用来发出请求的函数:
function getDistance()
{
//Find the distance
$.getJSON("https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=place_id:" + $("#autocompleteDeparture").data("place_id") + "&destinations=place_id:" + $("#autocompleteArrival").data("place_id") + "&key=MY_API_KEY0&callback=?", function(data) {
data = JSON.parse(data);
console.log(data);
});
}
如果我检查请求,它运行成功并返回正确的 JSON 数据:
{
"destination_addresses" : [ "9 Coach Ln, Belmont, Lower Hutt 5010, New Zealand" ],
"origin_addresses" : [ "3/30 Rata St, Naenae, Lower Hutt 5011, New Zealand" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "4.9 km",
"value" : 4934
},
"duration" : {
"text" : "8 mins",
"value" : 509
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
最佳答案
经过进一步挖掘,我发现 API 不支持 JSONP,我可以像这样通过 JavaScript 直接使用距离矩阵服务:
function getDistance()
{
//Find the distance
var distanceService = new google.maps.DistanceMatrixService();
distanceService.getDistanceMatrix({
origins: [$("#autocompleteDeparture").val()],
destinations: [$("#autocompleteArrival").val()],
travelMode: google.maps.TravelMode.WALKING,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true,
avoidHighways: false,
avoidTolls: false
},
function (response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
console.log('Error:', status);
} else {
console.log(response);
$("#distance").text(response.rows[0].elements[0].distance.text).show();
$("#duration").text(response.rows[0].elements[0].duration.text).show();
}
});
}
关于javascript - 使用 Javascript 查询 Google Distance Matrix API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38159768/