Google Maps Elevation Service

时间:2013-04-01 18:15:36

标签: google-maps elevation

我有这个功能,点击一个按钮就可以调用它。该功能在预定位置创建标记。然后我使用提升服务给定点。当我单击按钮时,警报消息(我将其放在那里进行诊断)显示“未定义”,然后出现标记(实际上标记应该在警告框之前显示!)。我已尽力确定问题的根源,但徒劳无功。有人可以帮我吗?谢谢。

  function buttonClicked () {
     addNode(someLat, someLong);
     alert(getElev(markers[0]));
  }

  function addNode(lat, lng) {
      var LatLng = new google.maps.LatLng(lat, lng);
      var marker = new google.maps.Marker({
         position: LatLng,
      });
      marker.setMap(map);
      markers.push(marker);
  }

  function getElev (marker) {
      var ht = 0;
      var locations = [];
      var clickedLocation = marker.getPosition();
      locations.push(clickedLocation);
      var positionalRequest = {
        'locations': locations
      }

      elevator.getElevationForLocations(positionalRequest, function (results, status) {
          if (status == google.maps.ElevationStatus.OK && results[0]) 
               ht = results[0].elevation;
      });
      return ht;
  }

2 个答案:

答案 0 :(得分:1)

在此处添加提醒,它应该可以使用。 getElev中的getElevationForLocations中的函数不会发生,而是异步调用。所以ht没有在getElev中设置。

  elevator.getElevationForLocations(positionalRequest, function (results, status) {
      if (status == google.maps.ElevationStatus.OK && results[0]){
           ht = results[0].elevation;
           alert(ht);
      }
  });

答案 1 :(得分:-1)

altitude = 0; // Declared with out "var" make it superglobal 
function buttonClicked () {
 addNode(someLat, someLong);
 alert(getAltitude());
}

function addNode(lat, lng) {
  var LatLng = new google.maps.LatLng(lat, lng);
  var marker = new google.maps.Marker({
     position: LatLng,
  });
  marker.setMap(map);
  markers.push(marker);
}

function getElev (marker) {
  var locations = [];
  var clickedLocation = marker.getPosition();
  locations.push(clickedLocation);
  var positionalRequest = {
    'locations': locations
  }

  elevator.getElevationForLocations(positionalRequest, function (results, status) {
      if (status == google.maps.ElevationStatus.OK && results[0]) 
           setAltitude(results[0].elevation);
  });
}

//getters and setters for altitude 
function setAltitude(a){
    altitude = a;
}
function getAltitude(){
    return altitude;
}