使用Javascript查询谷歌距离矩阵API
Using Javascript to query Google Distance Matrix API
我不是很流利的Javascript,但我试图建立一个简单的web应用程序使用它来尝试和学习更多。
我想使用谷歌距离矩阵API让我查询两个地址之间的距离。
我有两个输入字段,使用谷歌的自动完成功能来获取地址,然后我使用地址的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();
}
});
}
- 从https://console.developers.google.com/获取api密钥
- 获取您希望找到的地点之间的距离的经纬度。将它们转换为拉丁文对象。
- 使用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计算距离并将其设置在表格中<td>
- 如何在谷歌地图api v3中获得无公里驾驶距离
- 谷歌距离矩阵 API 没有输出
- 在谷歌地图API JS V3上显示距离用户当前位置最近的多个标记,距离30公里
- 将谷歌地图 api 距离矩阵结果限制为国家/地区
- 谷歌API正在计算无效地址的距离
- 搜索的地址与谷歌地图 api v3 上最近的现有地标之间的距离
- 无法使用谷歌地图 API v3 计算道路距离
- 如何使用谷歌地图 API V2 计算总距离
- 将 Google Apps API 密钥与距离矩阵结合使用
- 如何理解“;距离“;Web Audio API面板节点的方法
- 我将如何计算点之间的距离谷歌地图Api V3
- 尝试使用谷歌API来比较邮政编码距离
- 两点之间的距离谷歌地图a是未定义的api v3
- 从谷歌地图API V3获取旅行距离和旅行时间
- 如何在谷歌地图API上通过城市+ zipCode获得距离
- 如何增加距离与谷歌地图api
- 谷歌位置Api找到附近的位置与当前位置和附近位置之间的距离排序
- 计算两个位置之间的距离谷歌地图Api
- 如何使用谷歌地图API计算从已知点到最近点的距离