使用 Javascript 查询 Google 距离矩阵 API
Using Javascript to query Google Distance Matrix API
我对 Javascript 不是很流利,但我正在尝试使用它构建一个简单的 Web 应用程序以尝试学习更多知识。
我想使用 Google 距离矩阵 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"
}
- 从 https://console.developers.google.com/
获取您的 api 密钥
- 获取您想要计算距离的地点的经纬度。将它们转换为 LatLng 对象。
- 使用 computeDistanceBetween 函数。
......
<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>
经过进一步挖掘,我发现 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 不是很流利,但我正在尝试使用它构建一个简单的 Web 应用程序以尝试学习更多知识。
我想使用 Google 距离矩阵 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"
}
- 从 https://console.developers.google.com/ 获取您的 api 密钥
- 获取您想要计算距离的地点的经纬度。将它们转换为 LatLng 对象。
- 使用 computeDistanceBetween 函数。
......
<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>
经过进一步挖掘,我发现 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();
}
});
}