2011-10-20 13 views
0

私はチタンreverseGeocoderを使用しようとしていますが、私は "スコープ"問題だと思う奇妙な問題があります。なぜ私は、最後のログ呼び出しが、そのスコープ内の変数を定義したときにnull値を返すのかを理解できません。Appceleratorチタン - 逆ジオコーダーと可変スコープの問題

var win = Titanium.UI.currentWindow; 
Ti.include('includes/db.js'); 

var city = null; 
var country = null; 

Titanium.Geolocation.reverseGeocoder( Titanium.UI.currentWindow.latitude, 
             Titanium.UI.currentWindow.longitude, 
             function(evt) { 

var places = evt.places; 

if (places && places.length) { 
city = places[0].city; 
country = places[0].country;  
} 
Ti.API.log(city + ', ' + country); // <<< RETURNS CORRECT VALUES 

}); 

Ti.API.log(city + ', ' + country); // <<< RETURNS NULL VALUES 
+0

非同期に見えますが、このライブラリを使用したことがないので、ajax呼び出しと同じ*正確な動作が得られます。ちょうど閉じたこの質問を参照してください:http://stackoverflow.com/questions/7833379/scope-of-javascript-variable – davin

+0

それは同様の状況です、私はジオコーダが完了した後に変数を割り当てる方法が必要です。 – bagwaa

+0

あなたはそれをデバイスで試しましたか、シミュレータを使用していますか? –

答えて

1

これは、Davin氏が説明した非同期呼び出しです。逆ジオコーディング関数内で関数を呼び出す必要があります。

私はあなたに与えることができるイベントベースの仕事です。イベントを作成し、イベントを発生させます。例:

Titanium.UI.currentWindow.addEventListener('gotPlace',function(e){ 
    Ti.API.log(e.city); // shows city correctly 
}); 

Titanium.Geolocation.reverseGeocoder( Titanium.UI.currentWindow.latitude, 
             Titanium.UI.currentWindow.longitude, 
             function(evt) { 

    var city, country, places = evt.places; 

    if (places && places.length) { 
     city = places[0].city; 
     country = places[0].country;  
    } 
    Ti.API.log(city + ', ' + country); // <<< RETURNS CORRECT VALUES 
    Titanium.UI.currentWindow.fireEvent('gotPlace',{'city': city, 'country': country}); 
}); 
+0

ありがとう、これは便利だった - 私はちょうど私の呼び出しがイベントの中にあったことを確認して終わった。 – bagwaa

関連する問題