[英]Using Javascript to query Google Distance Matrix API
I'm not very fluent with Javascript, but am trying to build a simple web app using it to try and learn a bit more.我对 Javascript 不是很流利,但我正在尝试使用它构建一个简单的 Web 应用程序来尝试学习更多内容。
I'm wanting to use the Google Distance Matrix API to let me query the distance between two addresses.我想使用 Google 距离矩阵 API 来查询两个地址之间的距离。
I have two input fields that use the autocomplete function of Google to get the address and then I use the place_id
of the addresses to make a query to the API.我有两个输入字段,它们使用 Google 的自动完成功能来获取地址,然后我使用地址的place_id
对 API 进行查询。
I believe I need to use JSONP to make the call to the API and get the data, but I'm having trouble using the response and I get the following error in my console:我相信我需要使用 JSONP 来调用 API 并获取数据,但是我在使用响应时遇到问题,并且在我的控制台中收到以下错误:
Uncaught SyntaxError: Unexpected token :未捕获的语法错误:意外标记:
I've been searching around and everyone is using PHP in conjunction with JSONP - however I'm wanting to avoid this and keep the whole process client-side.我一直在四处寻找,每个人都将 PHP 与 JSONP 结合使用 - 但是我想避免这种情况并将整个过程保留在客户端。
How can I make the request and then use the JSON response that is returned?如何发出请求,然后使用返回的 JSON 响应?
Here is the function that I am using to make the request at the moment:这是我目前用来发出请求的函数:
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);
});
}
If I check the request, it is running successfully and returning the correct JSON 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"
}
After some more digging I found that the API does not support JSONP and that I could use the distance matrix service directly through JavaScript like so:经过更多的挖掘,我发现 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();
}
});
}
...... ......
<script src="https://maps.googleapis.com/maps/api/js?key=<API-KEY>&libraries=geometry&language=en&callback=initMap" async defer></script>
<script type="text/javascript">
function initMap(){
srcLocation = new google.maps.LatLng(19.075984, 72.877656);
dstLocation = new google.maps.LatLng(12.971599, 77.594563);
var distance = google.maps.geometry.spherical.computeDistanceBetween(srcLocation, dstLocation)
console.log(distance/1000); // Distance in Kms.
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.