簡體   English   中英

從谷歌地圖距離 API 將 JSON 數據讀取到網頁/html 表單中

[英]Reading JSON data into a webpage/html form from Google Maps Distance API

我對谷歌地圖距離 API 很陌生。 我正在嘗試創建一個表格,使用 long 和 lat 計算兩點之間的距離。

<a href="https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=53.487362,-2.227197&destinations=51.516595,-0.129279&key=API_KEY">
click here for distance
</a>

單擊該鏈接會給我一個 JSON 格式的結果頁面。

l

我如何讀取“距離:文本”(209 英里)數據並將值放入同一頁面上的<div><input>中。

提前致謝。

看起來您需要在客戶端獲取並顯示此數據,因此您應該使用 JavaScript 調用客戶端距離矩陣服務。 不是 web 服務(稱為服務器端)。 例如:

HTML

<button id="distance-btn" onClick="getDistance()">
  Click here for distance
</button>
<div id="distance"></div>

JS

function getDistance() {
  const origin = '53.487362,-2.227197';
  const destination = '51.516595,-0.129279';

  var distanceService = new google.maps.DistanceMatrixService();
  distanceService.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: 'DRIVING',
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    avoidHighways: false,
    avoidTolls: false
  }, function(response, status) {
    if (status !== 'OK') {
      alert('Error was: ' + status);
    } else {
      const distance = response.rows[0].elements[0].distance.text
      document.getElementById('distance').innerText = distance;
    }
  });
}

工作jsfiddle

話雖如此,如果您只想計算 1 個起點和 1 個目的地之間的距離,那么最好使用Directions 服務 看看這個其他的小提琴

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM