2017-07-16 1513 views
0

我想把地理位置功能(获取纬度和经度)放入一个库并返回经度和纬度,因为在整个应用程序中调用坐标。我可以从controller.js调用geo库,lat和long显示在控制台中,但是如何在controller.js的调用函数中使用坐标如何将库中的变量传递给Appcelerator/Titanium中的控制器?

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

};

controller.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; 

回答

1

创建这个可重用库是一个伟大的想法,你是在正确的道路上。 getCurrentPosition的挑战在于它是异步的,所以我们必须从它中获取数据。

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

使用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发出网络请求。 Here是一个类似的示例,您只需通过创建HTTPClient请求来为地理位置查询构建库,即可尝试执行此操作。

+0

非常感谢亚当明确的解释。特别是“基本上移动那个内容......”的部分。这是我没有得到的最​​后一个缺失部分。 – user24957

相关问题