0


从函数中取回高程值时,我遇到了一些问题。我无法获得该值。如果有人对此有解决方案,那就太好了。
这是我的代码:

function getElevation(latLng) {
  seaLevel = 'Error';
  var locations = [];
  locations.push(latLng);
  //Create a LocationElevationRequest object using the array[0] value
  var positionalRequest = {
    'locations': locations
  }
  //Initiate the location request
  elevationService.getElevationForLocations(positionalRequest, function(results, status) {
    if (status == google.maps.ElevationStatus.OK) {
      // Retrieve the first result
      if (results[0]) {
        var seaLvl = parseFloat(results[0].elevation.toFixed(1));
      }
      dropElevation(seaLvl);
    }
      document.getElementById("response").innerHTML = seaLevel;
  });
  function dropElevation(tmpLevel) {
    //alert(tmpLevel); at this point the value is correct
    seaLevel = tmpLevel;
  }
  return seaLevel; //at this point the value is always as defined above
} //End function (getElevation)

它的调用如下所示:

var seaLvl = getElevation(latLng);

提前感谢告诉我我做错了什么
Guido

4

1 回答 1

0

海拔服务是异步的。您必须在回调例程中使用该值。像这样的东西:

elevationService.getElevationForLocations(positionalRequest, function(results, status)  
{
  if (status == google.maps.ElevationStatus.OK) {
    // Retrieve the first result
    if (results[0]) {
      var seaLvl = parseFloat(results[0].elevation.toFixed(1));
      dropElevation(seaLvl);
      document.getElementById("response").innerHTML = seaLevel;
    } else {
      alert("no result");
    }
   }
 });

像这样的东西:

var seaLvl = getElevation(latLng);

将不起作用(在消息从服务器返回之前,该值不可用)。

于 2012-08-24T06:04:09.893 回答