1

我对 Javascript 不是很流利,但我正在尝试使用它构建一个简单的 Web 应用程序来尝试学习更多内容。

我想使用谷歌距离矩阵 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"
}
4

2 回答 2

8

经过一番挖掘,我发现 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();
        }
    });
  }
于 2016-07-03T04:55:42.087 回答
1
  1. 从https://console.developers.google.com/获取您的 api 密钥
  2. 获取您希望查找距离的地方的纬度和经度。将它们转换为 LatLng 对象。
  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>
于 2016-07-02T12:11:05.640 回答