2012-02-19 17 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; 
} 

Bu yüzden getAddr'i aradığımda tanımsızlaşıyorum, ayrıca elma önce ve sonra armut uyarılır. Google haritalarının eşzamansız olarak coğrafi harita oluşturduğunu, ancak bu işi yapmanın bir yolu olduğunu anlıyorum.Google maps geocoder bekleniyor mu?

cevap

10

Bunu böyle yapamazsınız. Google'ın coğrafi kodlayıcısına eşzamansız bir çağrınız var, bu da getAddr'ın sonuçları döndürmesini sağlayamayacağınız anlamına gelir.

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

Ve sonra böyle kodunda kullanmak: Bunun yerine böyle bir şey yapması gerektiğini

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); 
    } 
} 
: Ayrıca daha durum doğrulaması ekleyebilir size isterseniz

Ve bunun gibi kullanabilirsiniz:

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

Harika bir örnek, teşekkür ederim! – g33kz0r