geo = function(options){
    geocoder.geocode( options, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var x = results;
            alert('pear');
            return x;
        } else {
            return -1;
            }
        });
    }

getAddr = function(addr){
    if(typeof addr != 'undefined' && addr != null) {
        var blah = geo({ address: addr, });
                    alert('apple');
                    return blah;
    }
    return -1;
}

因此,当我调用getAddr时,会得到未定义的信息,同时也会首先提醒苹果,然后提醒梨。我意识到google异步映射地理编码,但是有没有办法使它工作呢?

最佳答案

您将无法那样做。您对Google的地址解析器进行了异步调用,这意味着您将无法让getAddr返回结果。相反,您应该执行以下操作:

getAddr = function(addr, f){
    if(typeof addr != 'undefined' && addr != null) {
        geocoder.geocode( { address: addr, }, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            f(results);
          }
        });
    }
    return -1;
}

然后在代码中使用如下代码:
getAddr(addr, function(res) {
  // blah blah, whatever you would do with
  // what was returned from getAddr previously
  // you just use res instead
  // For example:
  alert(res);
});

编辑:如果您想也可以添加更多状态验证:
getAddr = function(addr, f){
    if(typeof addr != 'undefined' && addr != null) {
        geocoder.geocode( { address: addr, }, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            f('ok', results);
          } else {
            f('error', null);
          }
        });
    } else {
      f('error', null);
    }
}

您可以像这样使用它:
getAddr(addr, function(status, res) {
  // blah blah, whatever you would do with
  // what was returned from getAddr previously
  // you just use res instead
  // For example:
  if (status == 'ok') {
    alert(res);
  } else {
    alert("Error")
  }
});

关于javascript - 等待谷歌 map 地理编码器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9345556/

10-12 00:30