如何获取提升请求的值

时间:2012-08-24 05:52:30

标签: google-maps-api-3


我面临一些问题,要从函数中获取高程值。我无法获得这个价值。如果有人有解决方案,那将会很棒 这是我的代码:

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);

先谢谢你告诉我我做错了什么 吉

1 个答案:

答案 0 :(得分:0)

Elevations服务是异步的。您必须使用回调例程中的值。像这样:

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);

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