簡體   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