指南针用于显示相对于地理北基点的方向。
步骤1 - 安装设备定向插件
打开命令提示符窗口并运行以下命令。
- C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device-orientation
步骤2 - 添加按钮
如果你按照我们的最后一个教程,你可能会注意到这个插件类似于加速插件。在本教程中,我们将遵循相同的概念。让我们在 index.html 中创建两个按钮。
- <button id = "getOrientation">GET ORIENTATION</button>
- <button id = "watchOrientation">WATCH ORIENTATION</button>
步骤3 - 添加事件监听器
现在我们将在 index.js 中的 onDeviceReady 函数中添加事件监听器。
- document.getElementById("getOrientation").addEventListener("click", getOrientation);
- document.getElementById("watchOrientation").addEventListener("click", watchOrientation);
步骤4 - 创建函数
我们将创建两个函数,一个获取当前加速度,另一个查看方向更改。您可以看到我们正在使用频率选项,因为我们想要每隔三秒观察一次更改。
- function getOrientation(){
- navigator.compass.getCurrentHeading(compassSuccess, compassError);
- function compassSuccess(heading) {
- alert('Heading: ' + heading.magneticHeading);
- };
- function compassError(error) {
- alert('CompassError: ' + error.code);
- };
- }
- function watchOrientation(){
- var compassOptions = {
- frequency: 3000
- }
- var watchID = navigator.compass.watchHeading(compassSuccess, compassError, compassOptions);
- function compassSuccess(heading) {
- alert('Heading: ' + heading.magneticHeading);
- setTimeout(function() {
- navigator.compass.clearWatch(watchID);
- }, 10000);
- };
- function compassError(error) {
- alert('CompassError: ' + error.code);
- };
- }
由于指南针插件几乎与加速插件相同,我们将在此时显示错误代码。 某些设备没有磁罗盘工作所需的磁性传感器。 如果您的设备没有它,您会得到以下错误。

转载本站内容时,请务必注明来自W3xue,违者必究。