0

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
bagwaa
  • 359
  • 1
  • 3
  • 12
  • Never used that library, although it looks asynchronous, so that would give it the *exact* same behaviour as an ajax call. Please see this question just closed: http://stackoverflow.com/questions/7833379/scope-of-javascript-variable – davin Oct 20 '11 at 09:00
  • it's a similar situation, I need a way to only assign the variables once the geocoder has completed. – bagwaa Oct 20 '11 at 09:36
  • did you try that on device or you are using a simulator? – Muhammad Zeeshan Oct 21 '11 at 04:43

1 Answers1

1

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});
});
Sukima
  • 9,965
  • 3
  • 46
  • 60
Rene Pot
  • 24,681
  • 7
  • 68
  • 92