2014-01-29 28 views
0

我有這個函數應該返回國家從經度和緯度開始,並將其分配給一個全局變量聲明的函數外。我知道Ajax中的a代表異步,我已經閱讀了stackoverflow上的每一個答案,但我無法修復它。谷歌地理編碼器 - 異步請求返回「未定義」值

function getLatLongDetail(myLatlng) { 

    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'latLng': myLatlng }, 
     function (results, status) { 
     var country = ""; 

      if (status == google.maps.GeocoderStatus.OK) { 
       if (results[0]) { 
        for (var i = 0; i < results[0].address_components.length; i++) { 
         var addr = results[0].address_components[i]; 
         // check if this entry in address_components has a type of country 
         if (addr.types[0] == 'country') 
          country = addr.long_name; 

        } 

        } 
        return country; // this doesn't work 

       } 

      } 

     }); 
} 


var Country = getLatLongDetail(myLatlng); 
alert(Country);// undefined 

我知道有關於回調函數的數百個問題,但他們都沒有爲我工作。

+0

很明顯嘛'add.long_name'不存在,你是越來越'undefined' –

+4

它看起來像這個問題http://stackoverflow.com/questions/14220321/how-要回來的答覆從ajax調用 – elclanrs

+1

是的 - 這是相同的症狀。相同的藥物也應該爲這個問題工作:-) – RaviH

回答

0

最後我做到了!下面的代碼:

function getLatLongDetail(myLatlng, fn) { 

    var geocoder = new google.maps.Geocoder(); 
    var country = ""; 
    var city = ""; 
    var address = ""; 
    var zip = ""; 
    var state = ""; 


    geocoder.geocode({ 'latLng': myLatlng }, 
     function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       if (results[0]) { 
        for (var i = 0; i < results[0].address_components.length; i++) { 
         var addr = results[0].address_components[i]; 
         // check if this entry in address_components has a type of country 
         if (addr.types[0] == 'country') 
         country = addr.long_name; 
        else if (addr.types[0] == ['locality'])  // City 
         city = addr.long_name; 
         else if (addr.types[0] == 'street_address') // address 1 
          address = address + addr.long_name; 
         else if (addr.types[0] == 'establishment') 
          address = address + addr.long_name; 
         else if (addr.types[0] == 'route') // address 2 
          address = address + addr.long_name; 
         else if (addr.types[0] == 'postal_code')  // Zip 
          zip = addr.short_name; 
         else if (addr.types[0] == ['administrative_area_level_1'])  // State 
          state = addr.long_name; 

        } 
       } 
      fn(country,city, address, zip, state); 
      } 
     }); 
    } 

    var mCountry; //global variable to store the country 
    vat mCity; //global variable to store the city 

getLatLongDetail(event.latLng, function(country,city, address, zip, state){ 
    mCountry = country; // now mCountry store the value from getLatLongDetail so I can save it in the database 
    mCity = city; 
    alert(address + zip + state); 
    }); 
相關問題