Search code examples
javascripttitaniumappceleratorappcelerator-mobile

Appcelerator Titanium - Reverse Geocoder and Variable Scope Issues


I am trying to use the titanium reverseGeocoder but I am having a strange issue which I think is a "scope" issue. I can't quite understand why the last log call I make returns null values when I have defined the variables in that scope.

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

Solution

  • This is an async call as Davin explained. You will have to call a function within the reverse geocode function.

    A suggestion I can give you is to work event-based. Create events, and fire events. An example:

    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});
    });