javascript - 移动设备上的绝对设备方向
问题描述
我试图以或多或少可靠的方式跨不同的移动设备(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"
我不知道在哪里可以了解以下推理我会错过多少设备,以及是否有更好的方法。
解决方案
对于 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
推荐阅读
- javascript - 如果输入步进值 > 0 addClass 到父 div 否则 removeClass
- r - R 错误 - 检查返回多个节点问题的远程错误
- c++ - 如何获取控制面板设置值,如字体大小
- java - Quartz执行方法不访问其他类或bean
- azure - 在 Azure Devops 中有条件地启动 ARM 模板部署
- regex - 正则表达式查找 + 运算符用于字符串连接的用法
- c++ - 将 std::array 推回 std::vector N 次的优雅方法
- ios - iPhone能否以编程方式用于蓝牙文件交换。(不使用 WiFi/NFC)
- node.js - 使用 vuejs 将图像上传到 Nodejs 服务器不起作用
- reactjs - 列表反应组件的多行辅助文本