2012-10-10 35 views
0

我試圖找出構造這個的最佳方法。我正在將外部html頁面加載到我的應用程序中。我有一個pageinit函數,用一些數據填充頁面。我也想拉這個電話的地理位置,但我需要檢查準備使用科爾多瓦的設備。如何確保Cordova準備就緒後該功能會被解除?在pageinit上梳理jquery mobile與cordova

我有以下內容,但每次都會收到一條提示「代碼:2,消息:無法啓動地理定位服務」。

var onSuccess = function(position) { 

    $('#latnlng').html(position.coords.latitude + ', ' + position.coords.longitude); 
}; 

function onFailure(error){ 
    alert('code: ' + error.code + '\n' + 
      'message: ' + error.message + '\n'); 
} 

jq(document).delegate("#singleCompany", "pageinit", function() { 
    retrieveCompany("527378C0D3465729A2F0B8C063396C5D"); 

    navigator.geolocation.getCurrentPosition(onSuccess,onFailure); 
}); 

我想我需要將其與下面的結合,但我不知道該如何

document.addEvenListener("deviceready", onDeviceReady, false); 

function onDeviceReady(){ 
navigator.geolocation.getCurrentPosition(onSuccess,onFailure); 
} 

回答

1

您應該從pageinit事件處理程序刪除navigator.geolocation...代碼並運行它deviceready事件處理中。 Cordova公開的地理位置API在deviceready事件觸發之前將不可用。

例如:

jq(document).delegate("#singleCompany", "pageinit", function() { 
    retrieveCompany("527378C0D3465729A2F0B8C063396C5D"); 
}); 

document.addEventListener("deviceready", onDeviceReady, false); 

function onDeviceReady(){ 
    navigator.geolocation.getCurrentPosition(onSuccess,onFailure); 
} 

UPDATE

要運行僅單個頁面地理位置代碼(即不開始頁面),則可以設置一個標誌,以確定是否事件已經開始。

例如:

var isDeviceReady = false; 
function onDeviceReady(){ 
    isDeviceReady = true; 
} 
document.addEventListener("deviceready", onDeviceReady, false); 

jq(document).delegate("#singleCompany", "pageinit", function() { 
    retrieveCompany("527378C0D3465729A2F0B8C063396C5D"); 

    if (isDeviceReady) { 
     navigator.geolocation.getCurrentPosition(onSuccess,onFailure); 
    } else { 
     //here you could set an interval to check the value of `isDeviceReady` and then call the geo-location code when it is set to `true` 
    } 
}); 
+0

但我如何才能運行#singleCompany'頁'的代碼? – David

+0

@David查看我的答案的更新。 – Jasper

+0

如果您想要使用第二種選擇,則可以使用全局延遲而不是布爾值。這樣你就不必輪詢。但更簡單的解決方案是在pageinit上保留地理位置,然後從onDeviceReady/wlCommonInit中加載頁面。這樣你就知道當頁面加載時,cordova已經準備就緒。 –

0

其實如果你正在使用工作燈,然後把你的代碼,或從wlEnvInit或wlCommonInit函數中調用函數就可以了。

+0

有趣。你能告訴我一個這樣的例子嗎? – David

+0

您可以將代碼放入Worklight init函數中。只有在設備準備好並且頁面準備就緒後纔會調用它。 –

相關問題