2017-07-16 1518 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

相關問題