首页 > 解决方案 > 移动设备上的绝对设备方向

问题描述

我试图以或多或少可靠的方式跨不同的移动设备(android + IOs)和浏览器获得绝对设备方向。我宁愿能够理解我收到的方向是否是相对的,而不是显示指南针而不是显示错误的值。
我已经来回搜索了好几天,但我还没有找到明确的答案(我是一个 javascript 和 web 开发新手)。
我看到Full-Tilt库应该正是这样做的,但它具有非商业许可证。我打算将此结果用于潜在的商业项目,此外,我想了解正在发生的事情。

如今,大多数设备定向事件都返回相对值。
Firefox 不支持deviceorientationabsolute并且它是一个实验性功能,当其他事情失败时我可以回退它,但它不能成为主要解决方案。

到目前为止,我已经进行了这一推理(伪代码):

if(mobile)
  if(webkitmobilecompassheading)
    window.addEventListener("deviceorientation", handleOrientationWebkit, true);
  else if(deviceorientationabsolute)
    window.addEventListener("deviceorientation", handleOrientationAbsolute, true);
  else
    "bad luck"   

我不知道在哪里可以了解以下推理我会错过多少设备,以及是否有更好的方法。

标签: javascriptandroidiosmobile

解决方案


对于 Android,它可以自动运行,对于 iOS,它需要单击才能启动。这是您可以使用的代码的一部分

startBtn.addEventListener("click", startCompass);

function startCompass() {
  if (isIOS) {
    DeviceOrientationEvent.requestPermission()
      .then((response) => {
        if (response === "granted") {
          window.addEventListener("deviceorientation", handler, true);
        } else {
          alert("has to be allowed!");
        }
      })
      .catch(() => alert("not supported"));
  } else {
    window.addEventListener("deviceorientationabsolute", handler, true);
  }
}

function handler(e) {
  const degree = e.webkitCompassHeading || Math.abs(e.alpha - 360);
}

完整教程在这里,也可以尝试演示 https://dev.to/orkhanjafarovr/real-compass-on-mobile-browsers-with-javascript-3emi


推荐阅读