【问题标题】:Appcelerator Titanium - Reverse Geocoder and Variable Scope IssuesAppcelerator Titanium - 反向地理编码器和可变范围问题
【发布时间】:2011-10-20 08:52:00
【问题描述】:

我正在尝试使用钛反向地理编码器,但我遇到了一个奇怪的问题,我认为这是一个“范围”问题。我不太明白为什么当我在该范围内定义变量时,我进行的最后一次日志调用返回空值。

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

【问题讨论】:

  • 从未使用过该库,尽管它看起来是异步的,因此它的行为exact 与 ajax 调用相同。请看这个刚刚结束的问题:stackoverflow.com/questions/7833379/…
  • 情况类似,我需要一种方法,仅在地理编码器完成后才分配变量。
  • 您是在设备上尝试过还是在使用模拟器?

标签: javascript titanium appcelerator appcelerator-mobile


【解决方案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});
});

【讨论】:

  • 谢谢,这很有用 - 我最终只是确保我的电话在活动中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
相关资源
最近更新 更多