Cordova 设备方向

指南针用于显示相对于地理北基点的方向。

步骤1 – 安装设备定向插件

打开命令提示符窗口并运行以下命令。

C:UsersusernameDesktopCordovaProject>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);
   };
	
}

由于指南针插件几乎与加速插件相同,我们将在此时显示错误代码。 某些设备没有磁罗盘工作所需的磁性传感器。 如果您的设备没有它,您会得到以下错误。

Cordova Compass Error

作者:andy,如若转载,请注明出处:https://www.web176.com/cordova/9656.html

(0)
打赏 支付宝 支付宝 微信 微信
andy的头像andy
上一篇 2023年2月14日
下一篇 2023年2月14日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注