获取谷歌地图标记的高度

get the elevation of a googlemaps' marker

我尝试获取地图上某个点的高程,但 googlemaps 的 API 建议的高程函数不起作用,我不知道为什么。 程序好像连函数都打不通

这是我的功能:

var elevationService = new google.maps.ElevationService();

var requestElevation = {
'locations': gmarkers[0].getPosition()};

elevationService.getElevationForLocations(requestElevation, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
  if (results[0]) {
    document.getElementById('denivele_circuit').value = parseFloat(results[0].elevation.toFixed(1)) + "mètres";
  }
}  });

你的代码出现 javascript 错误:Uncaught InvalidValueError: in property locations: not an Array

LocationElevationRequest中的locations属性必须是数组

from the documentation for google.maps.LocationElevationRequest object specification

An elevation request sent by the ElevationService containing the list of discrete coordinates (LatLngs) for which to return elevation data.

Properties

locations Type: Array

The discrete locations for which to retrieve elevations.

var requestElevation = {
  'locations': [gmarkers[0].getPosition()]
};

proof of concept fiddle

代码片段:

var gmarkers = [];

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var marker = new google.maps.Marker({
    position: map.getCenter(),
    map: map
  });
  gmarkers.push(marker);
  var elevationService = new google.maps.ElevationService();

  var requestElevation = {
    'locations': [gmarkers[0].getPosition()]
  };

  elevationService.getElevationForLocations(requestElevation, function(results, status) {
    if (status == google.maps.ElevationStatus.OK) {
      if (results[0]) {
        document.getElementById('denivele_circuit').value = parseFloat(results[0].elevation.toFixed(1)) + " mètres";
      }
    }
  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="denivele_circuit" />
<div id="map_canvas"></div>