海拔高度服務

總覽

海拔高度服務可為地表上的任何位置提供海拔高度資料,洋底深層位置也包含在內 (以負值表示)。如果 Google 無法針對您要求的精確位置提供確切的海拔高度測量值,這項服務會插入並傳回以四個最近的位置算出的平均值。

ElevationService 物件提供簡易的介面,可用來查詢地表位置的海拔高度資料。此外,您也可以要求路徑沿途的海拔高度取樣資料,以便計算路線沿途的海拔高度等距變化值。ElevationService 物件會與 Google Maps API 海拔高度服務進行通訊,以接收海拔高度要求並傳回海拔高度資料。

您可以使用海拔高度服務,開發健行和單車應用程式、行動定位應用程式,或是低解析度勘測應用程式。

開始使用

請先確認在 Google Cloud 控制台中,針對您為 Maps JavaScript API 設定的同一個專案啟用 Elevation API,再使用 Maps JavaScript API 中的海拔高度服務。

如要查看已啟用的 API 清單,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台
  2. 按一下「選取專案」按鈕,選取您為 Maps JavaScript API 設定的專案,然後點選「開啟」
  3. 在「資訊主頁」的 API 清單中,找出 Elevation API
  4. 如果在清單中看到該 API,就表示一切就緒。如果「沒有」看到這個 API,請按照下列步驟進行啟用:
    1. 選取頁面頂端的「啟用 API」,即會顯示「程式庫」分頁。或者,您也可以從左側選單中選取「程式庫」
    2. 搜尋「Elevation API」,然後從結果清單中選取該 API。
    3. 選取「啟用」。這個程序完成後,「資訊主頁」的 API 清單就會顯示「Elevation API」

定價和政策

定價

自 2018 年 7 月 16 日起,地圖介面集、路徑介面集和地點介面集採用新的「即付即用」定價方案,如要進一步瞭解新的 JavaScript 海拔高度服務使用費和用量限制,請參閱 Elevation API 的「用量與計費」一文。

政策

使用海拔高度服務時,必須遵守 Elevation API 的既定政策

海拔高度要求

Google Maps API 必須呼叫外部伺服器,因此海拔高度服務是以非同步的方式存取。基於這個理由,您必須傳遞在完成要求後執行的「回呼」方法。這個回呼方法會處理結果。請注意,海拔高度服務會傳回狀態碼 (ElevationStatus) 以及獨立 ElevationResult 物件的陣列。

ElevationService 會處理兩種要求:

  • 使用 getElevationForLocations() 方法針對獨立且不連續的位置發出的要求。系統會使用 LocationElevationRequest 物件,將一或多個位置的清單傳遞至這個方法。
  • 使用 getElevationAlongPath() 方法針對路徑沿途一連串的接續點發出的海拔高度要求。系統會將 PathElevationRequest 物件內一組已排序的路徑端點傳遞至這個方法。要求路徑沿途的海拔高度時,您必須同時傳遞一個參數來指出路徑沿途要採用的取樣數量。

這些方法也都必須傳遞一種「回呼」方法,來處理傳回的 ElevationResultElevationStatus 物件。

位置海拔高度要求

LocationElevationRequest 物件常值包含下列欄位:

{
  locations[]: LatLng
}

locations (必要):定義要傳回海拔高度資料的地表位置。這個參數會採用 LatLng 的陣列。

只要不超過服務配額,您可以在陣列中傳送任意數量的多個座標。請注意,傳遞多個座標時,任何傳回資料的解析度準確性,可能會比只要求單一座標資料時更低。

路徑海拔高度取樣要求

PathElevationRequest 物件常值包含下列欄位:

{
  path[]: LatLng,
  samples: Number
}

這些欄位的說明如下:

  • path (必要):定義要傳回海拔高度資料的地表路徑。path 參數會使用包含兩個或多個 LatLng 物件的陣列,來定義包含兩對或多對已排序 {latitude,longitude} 的組合。
  • samples (必要):指定要傳回海拔高度資料的路徑沿途取樣點數量。samples 參數會將指定的 path 分割為路徑沿途中一組已排序的等距點。

與位置要求一樣,path 參數會指定一組經緯度值。然而與位置要求不同的是,path 會指定一組已排序的端點。路徑要求不會傳回端點的海拔高度資料,而是會沿著路徑長度取樣,且每個取樣點之間的距離均相等 (包含端點)。

海拔高度回應

對於每個有效的要求,海拔高度服務會在定義的回呼中傳回一組 ElevationResult 物件以及一個 ElevationStatus 物件。

海拔高度狀態

每個海拔高度要求都會在回呼函式內傳回一個 ElevationStatus 代碼,這個 status 代碼包含下列其中一個值:

  • OK:表示已成功完成服務要求
  • INVALID_REQUEST:表示服務要求的格式有誤
  • OVER_QUERY_LIMIT:表示要求者已超出配額
  • REQUEST_DENIED:表示服務可能因參數無效而未完成要求
  • UNKNOWN_ERROR:表示發生未知錯誤

您應該檢查這個狀態碼是否為 OK,以便確認回呼是否成功。

海拔高度結果

成功時,回呼函式的 results 引數會包含一組 ElevationResult 物件。這些物件包含下列元素:

  • 位置的 location 元素 (包含 LatLng 物件),此位置用於計算海拔高度資料。請注意,在路徑要求中,location 元素的組合會包含路徑沿途的取樣點。
  • elevation 元素:表示位置的海拔高度 (以公尺為單位)。
  • resolution 值:表示插入海拔高度的資料點之間的最遠距離 (以公尺為單位)。如果解析度不明,就不會顯示這個屬性。請注意,傳遞多個點時,海拔高度資料會變得較不精確 (resolution 值較大)。如要取得某一點最準確的海拔高度值,請單獨進行查詢。

海拔高度範例

下方程式碼會使用 LocationElevationRequest 物件,將地圖點擊解譯為海拔高度要求:

TypeScript

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 8,
      center: { lat: 63.333, lng: -150.5 }, // Denali.
      mapTypeId: "terrain",
    }
  );
  const elevator = new google.maps.ElevationService();
  const infowindow = new google.maps.InfoWindow({});

  infowindow.open(map);

  // Add a listener for the click event. Display the elevation for the LatLng of
  // the click inside the infowindow.
  map.addListener("click", (event) => {
    displayLocationElevation(event.latLng, elevator, infowindow);
  });
}

function displayLocationElevation(
  location: google.maps.LatLng,
  elevator: google.maps.ElevationService,
  infowindow: google.maps.InfoWindow
) {
  // Initiate the location request
  elevator
    .getElevationForLocations({
      locations: [location],
    })
    .then(({ results }) => {
      infowindow.setPosition(location);

      // Retrieve the first result
      if (results[0]) {
        // Open the infowindow indicating the elevation at the clicked position.
        infowindow.setContent(
          "The elevation at this point <br>is " +
            results[0].elevation +
            " meters."
        );
      } else {
        infowindow.setContent("No results found");
      }
    })
    .catch((e) =>
      infowindow.setContent("Elevation service failed due to: " + e)
    );
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 8,
    center: { lat: 63.333, lng: -150.5 },
    mapTypeId: "terrain",
  });
  const elevator = new google.maps.ElevationService();
  const infowindow = new google.maps.InfoWindow({});

  infowindow.open(map);
  // Add a listener for the click event. Display the elevation for the LatLng of
  // the click inside the infowindow.
  map.addListener("click", (event) => {
    displayLocationElevation(event.latLng, elevator, infowindow);
  });
}

function displayLocationElevation(location, elevator, infowindow) {
  // Initiate the location request
  elevator
    .getElevationForLocations({
      locations: [location],
    })
    .then(({ results }) => {
      infowindow.setPosition(location);
      // Retrieve the first result
      if (results[0]) {
        // Open the infowindow indicating the elevation at the clicked position.
        infowindow.setContent(
          "The elevation at this point <br>is " +
            results[0].elevation +
            " meters."
        );
      } else {
        infowindow.setContent("No results found");
      }
    })
    .catch((e) =>
      infowindow.setContent("Elevation service failed due to: " + e)
    );
}

window.initMap = initMap;
查看範例

試用範例

下例會使用 Google Visualization API,以一組指定座標畫出一條折線,並顯示路徑沿途的海拔高度資料 (您必須使用 Google Common Loader 載入這個 API)。海拔高度要求是使用 PathElevationRequest 來建構:

TypeScript

// Load the Visualization API and the columnchart package.
// @ts-ignore TODO update to newest visualization library
google.load("visualization", "1", { packages: ["columnchart"] });

function initMap(): void {
  // The following path marks a path from Mt. Whitney, the highest point in the
  // continental United States to Badwater, Death Valley, the lowest point.
  const path = [
    { lat: 36.579, lng: -118.292 }, // Mt. Whitney
    { lat: 36.606, lng: -118.0638 }, // Lone Pine
    { lat: 36.433, lng: -117.951 }, // Owens Lake
    { lat: 36.588, lng: -116.943 }, // Beatty Junction
    { lat: 36.34, lng: -117.468 }, // Panama Mint Springs
    { lat: 36.24, lng: -116.832 },
  ]; // Badwater, Death Valley

  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 8,
      center: path[1],
      mapTypeId: "terrain",
    }
  );

  // Create an ElevationService.
  const elevator = new google.maps.ElevationService();

  // Draw the path, using the Visualization API and the Elevation service.
  displayPathElevation(path, elevator, map);
}

function displayPathElevation(
  path: google.maps.LatLngLiteral[],
  elevator: google.maps.ElevationService,
  map: google.maps.Map
) {
  // Display a polyline of the elevation path.
  new google.maps.Polyline({
    path: path,
    strokeColor: "#0000CC",
    strokeOpacity: 0.4,
    map: map,
  });

  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  // Initiate the path request.
  elevator
    .getElevationAlongPath({
      path: path,
      samples: 256,
    })
    .then(plotElevation)
    .catch((e) => {
      const chartDiv = document.getElementById(
        "elevation_chart"
      ) as HTMLElement;

      // Show the error code inside the chartDiv.
      chartDiv.innerHTML = "Cannot show elevation: request failed because " + e;
    });
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation({ results }: google.maps.PathElevationResponse) {
  const chartDiv = document.getElementById("elevation_chart") as HTMLElement;

  // Create a new chart in the elevation_chart DIV.
  const chart = new google.visualization.ColumnChart(chartDiv);

  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  const data = new google.visualization.DataTable();

  data.addColumn("string", "Sample");
  data.addColumn("number", "Elevation");

  for (let i = 0; i < results.length; i++) {
    data.addRow(["", results[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  chart.draw(data, {
    height: 150,
    legend: "none",
    // @ts-ignore TODO update to newest visualization library
    titleY: "Elevation (m)",
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// Load the Visualization API and the columnchart package.
// @ts-ignore TODO update to newest visualization library
google.load("visualization", "1", { packages: ["columnchart"] });

function initMap() {
  // The following path marks a path from Mt. Whitney, the highest point in the
  // continental United States to Badwater, Death Valley, the lowest point.
  const path = [
    { lat: 36.579, lng: -118.292 },
    { lat: 36.606, lng: -118.0638 },
    { lat: 36.433, lng: -117.951 },
    { lat: 36.588, lng: -116.943 },
    { lat: 36.34, lng: -117.468 },
    { lat: 36.24, lng: -116.832 },
  ]; // Badwater, Death Valley
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 8,
    center: path[1],
    mapTypeId: "terrain",
  });
  // Create an ElevationService.
  const elevator = new google.maps.ElevationService();

  // Draw the path, using the Visualization API and the Elevation service.
  displayPathElevation(path, elevator, map);
}

function displayPathElevation(path, elevator, map) {
  // Display a polyline of the elevation path.
  new google.maps.Polyline({
    path: path,
    strokeColor: "#0000CC",
    strokeOpacity: 0.4,
    map: map,
  });
  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  // Initiate the path request.
  elevator
    .getElevationAlongPath({
      path: path,
      samples: 256,
    })
    .then(plotElevation)
    .catch((e) => {
      const chartDiv = document.getElementById("elevation_chart");

      // Show the error code inside the chartDiv.
      chartDiv.innerHTML = "Cannot show elevation: request failed because " + e;
    });
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation({ results }) {
  const chartDiv = document.getElementById("elevation_chart");
  // Create a new chart in the elevation_chart DIV.
  const chart = new google.visualization.ColumnChart(chartDiv);
  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  const data = new google.visualization.DataTable();

  data.addColumn("string", "Sample");
  data.addColumn("number", "Elevation");

  for (let i = 0; i < results.length; i++) {
    data.addRow(["", results[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  chart.draw(data, {
    height: 150,
    legend: "none",
    // @ts-ignore TODO update to newest visualization library
    titleY: "Elevation (m)",
  });
}

window.initMap = initMap;
查看範例

試用範例