我正在试图找出构建它的最佳方法。我正在将一个外部html页面加载到我的应用程序中。我有一个pageinit函数,用一些数据填充页面。我也想用这个拉电话的地理位置,但我需要检查设备准备使用cordova。当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);
}
答案 0 :(得分:1)
您应该从navigator.geolocation...
事件处理程序中删除pageinit
代码,并在deviceready
事件处理程序中运行它。 Cordova公开的地理位置API在deviceready
事件触发前无法使用。
例如:
jq( document ).delegate("#singleCompany", "pageinit", function() {
retrieveCompany("527378C0D3465729A2F0B8C063396C5D");
});
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(){
navigator.geolocation.getCurrentPosition(onSuccess,onFailure);
}
<强>更新强>
要仅为单个页面(不是起始页面)运行地理位置代码,您可以设置一个标志以确定deviceready
事件是否已被触发。
例如:
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`
}
});
答案 1 :(得分:0)
实际上如果您正在使用Worklight,那么从wlEnvInit或wlCommonInit函数中放置代码或调用函数就可以了。