2010-04-14 106 views
0

如何返回codeAddress函數的latlon變量。返回latlon不起作用,可能是因爲範圍,但我不確定如何使其工作。函數返回函數中的方法回調數據中的變量

function codeAddress(addr) { 
     if (geocoder) { 
      geocoder.geocode({ 'address': addr}, function(results, status) { 
        if (status == google.maps.GeocoderStatus.OK) { 
        var latlon = results[0].geometry.location.c+","+results[0].geometry.location.b; 
        } else { 
         alert("Geocode was not successful for the following reason: " + status); 
        } 

     }); 
    } 
    } 

回答

0

您不能從codeAddress返回geocoder.geocode的結果,因爲geocoder.geocode會將其結果返回給您提供的回調/閉包。你必須繼續使用一個回調作爲你的函數codeAddress的參數。

返回給您geocoder.geocode回調到geocoder.geocode的任何回調在您的應用程序中都沒有任何意義。您必須從您提供給geocoder.geocode的回調中調用應用程序中的某個函數。

這在API的Geocoding Requests部分進行了說明。

+0

謝謝我在jquery ajax回調中遇到過這麼多次,並且今天沒有想到。感謝大腦的提升。 – aran 2010-04-15 14:50:55

1

聲明一個變量外功能,將其設置在內部功能和外部返回它:

function codeAddress(addr) { 
    var returnCode = false; 
    if (geocoder) { 
    geocoder.geocode({ 'address': addr}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     var latlon = results[0].geometry.location.c+","+results[0].geometry.location.b; 
     returnCode = true; 
     } else { 
     alert("Geocode was not successful for the following reason: " + status); 
     } 
    }); 
    } 
    return returnCode; 
} 

注意:這隻會工作,如果內部函數運行的時候了!

+0

它可能無法執行,因爲geocoder.geocode可能執行異步方法調用,其中返回結果的唯一方法是通過提供的回調。 – Ernelli 2010-04-14 23:08:02