使用JavaScript访问iPhone指南针

7

您是否想知道在使用JavaScript时是否可以在Safari中访问iPhone指南针?我看到了如何访问GPS,但我无法弄清楚指南针的访问方法。


1
刚刚注意到今天发布了W3C Compass API草案:http://dev.w3.org/2009/dap/system-info/compass.html,也许这种功能会在不久的将来到来。 - Drew Dara-Abrams
在iOS5中,您可以使用webkitCompassHeading访问指南针,请查看此文档 - user943938
4个回答

4

iOS上,您可以像这样检索罗盘值。

window.addEventListener('deviceorientation', function(e) {
    console.log( e.webkitCompassHeading );
}, false);

想要了解更多信息,请阅读苹果设备方向事件文档

希望能对你有所帮助。


3

1
这个答案已经不再正确了,iOS 4.2提供了webkitCompassHeading,请查看awoodland的答案。 - ianj

2

对于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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接