概览
“海拔”服务提供地球表面上各位置的海拔数据,包括海底深处位置的海拔数据(返回负值)。如果 Google 不具有您所请求的确切位置的精确海拔高度测量值,服务将进行插值计算,利用四个最接近位置的数据返回一个平均值。
ElevationService 对象为您提供了一个简单的查询接口,用于查询地图上各位置的海拔数据。此外,您还可以请求沿着路径的采样海拔数据,这样您就可以计算沿着路线的等距海拔变化。ElevationService 对象与 Google Maps API Elevation Service 通信,后者接收海拔请求并返回海拔数据。
使用“海拔”服务,您可以开发远足和骑行应用、移动定位应用或低分辨率测量应用。
入门指南
在 Google Maps JavaScript API 中使用海拔服务之前,首先要确保在为 Google Maps JavaScript API 设置的同一项目的 Google API Console 中启用 Google Maps Elevation API。
要查看已启用 API 的列表,请执行以下操作:
- 转至 Google API Console。
- 点击 Select a project 按钮,然后选择为 Google Maps JavaScript API 设置的同一项目并点击 Open。
- 在 Dashboard 上的 API 列表中,寻找 Google Maps Elevation API。
- 如果在列表中看到该 API,则大功告成。如果未列出该 API,请执行以下操作将其启用:
- 在页面顶部,选择 ENABLE API 以显示 Library 标签。也可从左侧菜单中选择 Library。
- 搜索 Google Maps Elevation API,然后从结果列表中选择它。
- 选择 ENABLE。流程完成时,Google Maps Elevation API 即会出现在 Dashboard 上的 API 列表中。
使用限额和政策
配额
对于海拔服务,具有以下使用限额:
搭配标准计划使用海拔服务
- 每天 2,500 次免费请求,按客户端与服务器端查询次数之和计算; 启用计费可获得更高每日配额,按 0.50 美元/1000 次额外请求计费,每日上限为
100,000 次请求。 - 每次请求 512 个位置。
- 每秒 50 次请求,按客户端与服务器端查询次数之和计算。
搭配高级计划使用海拔服务
- 10 万个请求的每日免费共享配额 (每 24 小时);根据每年购买的 Maps API 额度申请的额外请求。
- 每次请求 512 个位置。
- 每个项目每秒 不受限制 次客户端请求。请注意,服务器端 API 有每秒 50 次请求的限制。
无论有多少位用户共享同一项目,均以用户会话为单位施加速率限制。
单位会话速率限制可防止将客户端服务用于批量请求。如果您想改为计算已知静态位置的海拔,请使用 Google Maps Elevation API 网络服务。
政策
必须按照所介绍的适用于 Google Maps Elevation API 的政策使用海拔服务。
海拔请求
由于 Google Maps API 需要调用外部服务器,因此访问“海拔”服务是异步进行的。为此,您需要传递一个在完成请求后执行的回调方法。此回调方法会对结果进行处理。请注意,“海拔”服务会返回一个状态代码 (ElevationStatus) 和一个包含各个 ElevationResult 对象的数组。
ElevationService 处理两种类型的请求:
- 对多个独立、分散的位置的请求,方法是:使用
getElevationForLocations()方法并使用LocationElevationRequest对象向其传递一个或多个位置列表。 - 对沿着一条路径的一系列相连点的海拔请求,方法是:使用
getElevationAlongPath()方法,并在PathElevationRequest对象内向其传递一组按顺序排列的路径顶点。请求沿着路径的各位置的海拔时,您还必须传递一个参数,用于指明您希望沿着该路径抽取多少个采样点。
以上各方法还必须传递一个回调方法,用于处理返回的 ElevationResult 和 ElevationStatus 对象。
位置海拔请求
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 对象将在地图上的点击操作转换为海拔请求。
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 63.333, lng: -150.5}, // Denali.
mapTypeId: 'terrain'
});
var elevator = new google.maps.ElevationService;
var infowindow = new google.maps.InfoWindow({map: map});
// Add a listener for the click event. Display the elevation for the LatLng of
// the click inside the infowindow.
map.addListener('click', function(event) {
displayLocationElevation(event.latLng, elevator, infowindow);
});
}
function displayLocationElevation(location, elevator, infowindow) {
// Initiate the location request
elevator.getElevationForLocations({
'locations': [location]
}, function(results, status) {
infowindow.setPosition(location);
if (status === 'OK') {
// 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');
}
} else {
infowindow.setContent('Elevation service failed due to: ' + status);
}
});
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 63.333, lng: -150.5}, // Denali.
mapTypeId: 'terrain'
});
var elevator = new google.maps.ElevationService;
var infowindow = new google.maps.InfoWindow({map: map});
// Add a listener for the click event. Display the elevation for the LatLng of
// the click inside the infowindow.
map.addListener('click', function(event) {
displayLocationElevation(event.latLng, elevator, infowindow);
});
}
function displayLocationElevation(location, elevator, infowindow) {
// Initiate the location request
elevator.getElevationForLocations({
'locations': [location]
}, function(results, status) {
infowindow.setPosition(location);
if (status === 'OK') {
// 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');
}
} else {
infowindow.setContent('Elevation service failed due to: ' + status);
}
});
}
以下示例构建一条由一组给定坐标构成的折线,并使用 Google Visualization API 显示沿着该路径的海拔数据。(您必须使用 Google Common Loader 加载此 API。)使用 PathElevationRequest 构建海拔请求:
// Load the Visualization API and the columnchart package.
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.
var 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
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: path[1],
mapTypeId: 'terrain'
});
// Create an ElevationService.
var 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
}, plotElevation);
}
// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
if (status !== 'OK') {
// Show the error code inside the chartDiv.
chartDiv.innerHTML = 'Cannot show elevation: request failed because ' +
status;
return;
}
// Create a new chart in the elevation_chart DIV.
var 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.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < elevations.length; i++) {
data.addRow(['', elevations[i].elevation]);
}
// Draw the chart using the data within its DIV.
chart.draw(data, {
height: 150,
legend: 'none',
titleY: 'Elevation (m)'
});
}
<div> <div id="map" style="height:250px;"></div> <div id="elevation_chart"></div> </div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://www.google.com/jsapi"></script> <!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
// Load the Visualization API and the columnchart package.
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.
var 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
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: path[1],
mapTypeId: 'terrain'
});
// Create an ElevationService.
var 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
}, plotElevation);
}
// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
if (status !== 'OK') {
// Show the error code inside the chartDiv.
chartDiv.innerHTML = 'Cannot show elevation: request failed because ' +
status;
return;
}
// Create a new chart in the elevation_chart DIV.
var 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.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation');
for (var i = 0; i < elevations.length; i++) {
data.addRow(['', elevations[i].elevation]);
}
// Draw the chart using the data within its DIV.
chart.draw(data, {
height: 150,
legend: 'none',
titleY: 'Elevation (m)'
});
}
