繁体   English   中英

使用Javascript查询Google Distance Matrix API

[英]Using Javascript to query Google Distance Matrix API

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

我想使用 Google 距离矩阵 API 来查询两个地址之间的距离。

我有两个输入字段,它们使用 Google 的自动完成功能来获取地址,然后我使用地址的place_id对 API 进行查询。

我相信我需要使用 JSONP 来调用 API 并获取数据,但是我在使用响应时遇到问题,并且在我的控制台中收到以下错误:

未捕获的语法错误:意外标记:

我一直在四处寻找,每个人都将 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. 获取您希望找到之间距离的地点的纬度和经度。 将它们转换为 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM