2012-01-02 75 views
2

所以我如何在函數內部的javascript函數外返回一個變量?

function find_coord(lat, lng) { 
       var smart_loc; 
     var latlng = new google.maps.LatLng(lat, lng); 
     geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 'latLng': latlng }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       smart_loc = new smart_loc_obj(results); 
      } else { 
       smart_loc = null; 
      } 
     }); 

     return smart_loc; 
} 

我想返回smart_loc變量/對象,但它始終是零,因爲函數的範圍(結果狀態)沒有達到在find_coord函數聲明的smart_loc。那麼如何在函數內部得到一個變量(結果,狀態)呢?

+1

我不認爲這是範圍問題。而是一個我還沒有定義的問題。 geocoder.geocode的作用是什麼?像一個AJAX調用? – PeeHaa 2012-01-02 03:30:25

+3

你不能那樣做。 「geocode()」函數是** asynchronous **,這意味着它不會立即運行;它在Google返回結果時運行。 – Pointy 2012-01-02 03:33:05

+0

,但該地理編碼在該功能運行之前不會運行,而地理編碼來自Google地圖地理編碼器 – Derek 2012-01-02 03:37:41

回答

0

你可以這樣做:

var smart_loc; 

function find_coord(lat, lng) { 
    var latlng = new google.maps.LatLng(lat, lng); 
    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'latLng': latlng }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      smart_loc = new smart_loc_obj(results); 
     } else { 
      smart_loc = null; 
     } 
    }); 
} 

或者,如果你需要運行一個功能時smart_loc變化:

function find_coord(lat, lng, cb) { 
      var smart_loc; 
    var latlng = new google.maps.LatLng(lat, lng); 
    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'latLng': latlng }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      smart_loc = new smart_loc_obj(results); 
     } else { 
      smart_loc = null; 
     } 

     cb(smart_loc); 
    }); 
} 

然後調用:

find_coord(lat, lng, function (smart_loc) { 
    // 
    // YOUR CODE WITH 'smart_loc' HERE 
    // 
}); 
相關問題