2012-01-02 11 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に到達していないので、それは常にnullです。では、関数内の変数(結果、状態)をどのように取得しますか?

あなたが行うことができます
+1

私はそれがあるとは思いません範囲の問題しかし、むしろ私はまだ問題は定義されていません。 'geocoder.geocode'は何をしますか? AJAXコールのようなもの? – PeeHaa

+3

できません。 "geocode()"関数は**非同期**です。つまり、すぐには実行されません。 Googleが結果を返すときに実行されます。 – Pointy

+0

ですが、関数が実行されるまでジオコードは実行されず、ジオコーダーはGoogleマップジオコーダーからのものです。 – Derek

答えて

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 
    // 
}); 
関連する問題