海拔服务

概览

海拔服务提供地球表面上各位置的海拔数据,包括洋底深处位置的海拔数据(返回负值)。对于您所请求的确切位置,如果 Google 没有掌握精确的海拔测量值,该服务将采用插值法进行计算,根据四个最接近的位置返回一个平均值。

ElevationService 对象提供一个简单的查询接口,用于查询地球上各位置的海拔数据。此外,您还可以请求路径沿线的抽样海拔数据,这样就可以计算路线沿线的等距海拔变化。ElevationService 对象与 Google Maps API 海拔服务通信,后者接收海拔请求并返回海拔数据。

借助海拔服务,您可以开发远足和骑行应用、移动定位应用或低分辨率测量应用。

开始使用

在使用 Maps JavaScript API 中的海拔服务之前,首先要确保在 Google Cloud 控制台中针对您为 Maps JavaScript API 设置的同一项目启用了 Elevation API。

若要查看已启用的 API 列表,请按以下步骤操作:

  1. 前往 Google Cloud 控制台
  2. 点击选择项目按钮,选择您为 Maps JavaScript API 设置的同一项目,然后点击打开
  3. 信息中心上的 API 列表中,查找 Elevation API
  4. 如果您在列表中看到该 API,就说明一切就绪。如果其中未列出该 API,请执行以下操作将其启用:
    1. 在页面顶部,选择启用 API 以显示标签页。或者,您也可以从左侧菜单中选择
    2. 搜索 Elevation API,然后从结果列表中选择它。
    3. 选择启用。该过程完成后,Elevation API 即会显示在信息中心上的 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;
查看示例

试用示例