2012-02-19 11 views
6
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 Mapsジオコードを非同期にマップすることを認識していますが、この作業を行う方法はありますか?Googleマップジオコーダを待っていますか?

答えて

10

このようにすることはできません。 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); 
}); 

EDIT:あなたがしたい場合は、より多くの状況の検証を追加することができます。

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") 
    } 
}); 
+0

すばらしい例、ありがとう! – g33kz0r

関連する問題