Rob88991
Rob88991

Reputation: 153

Appcelerator/Titanium - Call variable from within function

I have some code as below, which gets the current location and then creates a variable with that information. I would like to use that variable outside of the function but so far everything I've tried has failed. The alert below works if it's within the function, but as soon as you put it outside it's blank. I've also tried creating global variables in alloy.js but that didn't seem to work either. I know this is very simple but need some more ideas :)

Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) { 
    alert('Error: ' + e.error); 
} else { 

    var params = {
        latitude: e.coords.latitude,
    };

    return params;

} 
});



alert(params);

Upvotes: 0

Views: 158

Answers (1)

miga
miga

Reputation: 4055

This is not related to Titanum but a basic javascript question. params is a local variable (inside the getCurrentPosition). You can create a global scope like this:

var coords;

Titanium.Geolocation.getCurrentPosition(function(e) {
    if (e.error) { 
        alert('Error: ' + e.error); 
    } else { 
        coords = {
            latitude: e.coords.latitude,
            longitude: e.coords.longitude,
        };
    } 
});

But keep in mind: coords might not be set straight away because it could take a bit until the getCurrentPosition function is finished or has the data.

Upvotes: 3

Related Questions