0

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

  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;
  }
4

2 回答 2

1

在此处添加警报,它应该可以工作。getElevationForLocations 中的函数不会出现在 getElev 中,而是异步调用。所以 ht 没有在 getElev 中设置。

  elevator.getElevationForLocations(positionalRequest, function (results, status) {
      if (status == google.maps.ElevationStatus.OK && results[0]){
           ht = results[0].elevation;
           alert(ht);
      }
  });
于 2013-04-01T23:13:42.740 回答
-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;
}
于 2015-12-09T22:04:26.817 回答