Search code examples
javascriptiosgeolocationtitaniumlatitude-longitude

How do I access/store latitude and longitude from Ti.Geolocation.getCurrentPosition?


I am using Titanium Studio (3.4.1) and writing in JavaScript for iOS and Android.

I am trying to get the device's latitude and longitude and return it to a function so that I could call on that function in another module and pass it to another function.

This is geo.js and inside I am loading Ti.Geolocation.getCurrentPosition and attempting to return the lattitude to the function getLat(). And then, make it available to app.js with exports.

exports.getLat = function(){
Ti.Geolocation.getCurrentPosition(function(e) {
    console.log(e);
    timeout : 10000;
    return JSON.stringify(e.coords.latitude);
});
};

This is app.js and it checks to see which platform the app is running. It sees its an iPhone and then requires geo.getLat(). After that I want to store the latitude into the variable lat and use it later to feed it to another function as a parameter, like getWdata(lat);

if (Ti.Platform.osname === 'android') {
    console.log('android version\n');
    var geo = require('geo');
    var lat = geo.getLat(0);
    var lng = geo.getLng(0);
    console.log('Android Coordinates: ' + lat, lng);    
        }

else if (Ti.Platform.osname === 'iphone' || 'ipad'){
    console.log('iOS version\n');
    var geo = require('geo');
    var lat = geo.getLat();
    geo.getLat();
    console.log('iOS Coordinates: ' + lat);
        }

Solution

  • You will need to use callback for accomplishing this task. The simple procedure is to pass a function (called callback) as parameter and instead using return; call the callback function.

    Also you need not to call two methods for fetching latitude/longitude, because it can be done using one method only.

    Example below :

    In geo.js:

    exports.getLatLong = function(callback){
        Ti.Geolocation.getCurrentPosition(function(e) {
            if (e.success) {
                Ti.API.info("Cords latitude" + e.coords.latitude);
                Ti.API.info("Cords longitude" + e.coords.longitude);
                callback(e.coords.latitude, e.coords.longitude);
            } else {
                alert("Unable to fetch cords");
            }
        });
    };
    

    Now in app.js, call the getLatLong function as:

    var geo = require('geo'), lat = 0, long = 0;
    geo.getLatLong(function(latitude,longitude) {
        lat = latitude;
        long = longitude;
    });
    

    Note : Use Ti.API.info instead of console.log.