使用Javascript查询谷歌距离矩阵API

Using Javascript to query Google Distance Matrix API

本文关键字:API 距离 谷歌 Javascript 查询 使用      更新时间:2023-09-26

我不是很流利的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();
        }
    });
  }
  1. 从https://console.developers.google.com/获取api密钥
  2. 获取您希望找到的地点之间的距离的经纬度。将它们转换为拉丁文对象。
  3. 使用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>