0

我正在尝试将地理定位功能(获取纬度和经度)放入库中并返回纬度和经度,因为在整个应用程序中都会调用坐标。我可以从controller.js 调用geo 库,lat 和long 显示在控制台中,但是如何在controller.js 调用函数中使用坐标呢?

在 app/lib/geo.js

exports.getLongLat = function checkLocation(){
if (Ti.Geolocation.locationServicesEnabled) {
    Titanium.Geolocation.getCurrentPosition(function(e) {
        if (e.error) {
            Ti.API.error('Error: ' + e.error);
            } else {
                Ti.API.info(e.coords);
                var latitude = e.coords.latitude;
                var longitude = e.coords.longitude;
                console.log("lat: " + latitude + " long: " + longitude);
            }
        });
    } else {
        console.log('location not enabled');
}

};

控制器.js

geolocation.getLongLat(); //this calls the library, but I don't know how I can get the coordinates "back" into the controller.js file for using it in the var args below.

var args ="?display_id=check_if_in_dp_mobile&args[0]=" + lat + "," + lon;
4

1 回答 1

1

为此创建一个可重用的库是一个好主意,而且您走在正确的道路上。挑战getCurrentPosition在于它是异步的,所以我们必须从它那里获取数据有点不同。

请注意在 geo.js 中,该行Titanium.Geolocation.getCurrentPosition(function(e) {...有一个函数被传递给getCurrentPosition. 这是一个回调函数,在手机接收到位置数据后执行。这是因为getCurrentPosition是异步的,这意味着该回调函数中的代码要到稍后的时间点才会执行。我在这里有一些关于异步回调的注释。

使用您的 getLongLat 函数,我们需要做的主要事情是向它传递一个回调,该回调又可以传递给 getCurrentPosition。像这样的东西:

exports.getLongLat = function checkLocation(callback){
    if (Ti.Geolocation.locationServicesEnabled) {
        //we are passing the callback argument that was sent from getLongLat
        Titanium.Geolocation.getCurrentPosition(callback);
    } else {
        console.log('location not enabled');
    }
};

然后当你执行该函数时,你会将回调传递给它:

//we moved our callback function here to the controller where we call getLongLat
geolocation.getLongLat(function (e) {
    if (e.error) {
        Ti.API.error('Error: ' + e.error);
    } else {
        Ti.API.info(e.coords);
        var latitude = e.coords.latitude;
        var longitude = e.coords.longitude;
        console.log("lat: " + latitude + " long: " + longitude);
    }
}); 

在这种情况下,我们基本上是将该函数的内容最初传递到您在控制器getCurrentPosition中调用的位置。getLongLat现在,当回调执行时,您将能够对坐标数据做一些事情。

Titanium 应用程序中发生回调的另一个地方是使用Ti.Network.HttpClient. 是一个类似的示例,您尝试通过仅通过发出 HTTPClient 请求为您的地理位置查询构建一个库来执行此操作。

于 2017-07-16T16:00:48.677 回答