只读一次指南针

时间:2013-12-19 21:38:54

标签: javascript cordova phonegap-plugins

所以我正在研究android的Android应用程序,我正在使用指南针插件。 我按照来自phonegap网站的说明,一切正常,除了一件事。

第一个示例(http://docs.phonegap.com/en/2.0.0/cordova_compass_compass.md.html#Compass)应该在警报中给出标题(度)一次,但值始终为0!但为什么呢?

所以我已经处理了代码,所以它看起来像第二个例子(没有按钮)。此代码检查en每秒显示度数。现在值不是0,而是介于1和360之间。 这是我想要的价值,但我不想每一秒,我只想要它一次。有没有办法只检查一次?

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

// Cordova is ready
function onDeviceReady() {
    navigator.compass.getCurrentHeading(onSuccess, onError);
}

// onSuccess: Get the current heading
function onSuccess(heading) {
    alert('Heading: ' + heading.magneticHeading);
}

// onError: Failed to get the heading
function onError(compassError) {
    alert('Compass Error: ' + compassError.code);
}

所以这是标准的javascript,这段代码应该给标题juist一次,但它总是给出0。

$(document).ready(function() {
// The watch id references the current `watchHeading`
var watchID = null;

// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
function onDeviceReady() {
    startWatch();
}

// Start watching the compass
function startWatch() {
    var options = { frequency: 100 };
    watchID = navigator.compass.watchHeading(onSuccess, onError, options);
}

// Stop watching the compass
function stopWatch() {
    if (watchID) {
        navigator.compass.clearWatch(watchID);
        watchID = null;
    }
}

// onSuccess: Get the current heading
function onSuccess(heading) {
    var element = document.getElementById('heading');
    element.innerHTML = heading.magneticHeading;

    if (heading.magneticHeading > 180) {
        document.getElementById('background').style.backgroundColor = 'green';
    } else {
        document.getElementById('background').style.backgroundColor = 'blue';
    }
}

// onError: Failed to get the heading
function onError(compassError) {
    alert('Compass error: ' + compassError.code);
}
});

此代码有效,但它会检查是否不是一次,而是多次检查。

2 个答案:

答案 0 :(得分:0)

如果没有看到你正在使用的完整代码,我会说第一个例子可能是零,因为设备没有准备好(你会注意到在第二个例子中,对watchHeading的调用直到deviceready事件触发)。

至于第二个问题,这是因为watchHeading不断请求反馈(由频率选项控制)。获得手表的ID后,您需要调用clearWatch并将该ID传递给停止。

如果您只想尝试获得单个标题,只需调用getHeading而不是watchHeading。但只有在设备准备就绪后才能这样做。

<强> --- ---编辑

这让我感到很烦恼,无法构建你的项目并在我的Droid 4上运行(运行4.1.2)。返回0 - 正常行为;这只是罗盘预热(类似于GPS,你想要丢弃你收到的第一个坐标,因为它们通常是陈旧的)。通常只需要一次通话即可将其加热,之后您将获得良好的数据。

由于你不想得到持续的反馈,我会在app start上预热指南针(只需调用getCurrentHeading一次),然后在需要时再次调用getCurrentHeading。

或者,继续并每隔几秒钟收到一次反馈,因为只是存储最新的罗盘标题并且保持指南针准备就没有坏处。然后,当您希望应用程序使用数据时,您可以只调用getCurrentHeading或使用存储的罗盘数据。

答案 1 :(得分:0)

你需要从onSuccess()内部调用stopWatch(),因为你告诉watchHeading()每100毫秒重复一次。