我可以使用 Javascript 获取 iOS 和 Android 的指南针方向吗?

2024-03-19

我可以跨平台使用 Javascript 来获取 iOS 和 Android(使用 Chrome)中的指南针方向,而不使用 PhoneGap 之类的东西吗?我知道iOS有设备方向事件 https://developer.apple.com/library/safari/documentation/SafariDOMAdditions/Reference/DeviceOrientationEventClassRef/DeviceOrientationEvent/DeviceOrientationEvent.html,但我在 Android 版 Chrome 上找不到任何等效项。


作为入门书,您应该回顾一下之前相关的 StackOverflow 答案 https://stackoverflow.com/a/21829819/320485并熟悉一般情况使用 DeviceOrientation 事件的实际注意事项 https://dev.opera.com/articles/w3c-device-orientation-usage/#practicalconsiderations在网络应用程序中。

我提供的简单解决方案我之前相关的 StackOverflow 答案 https://stackoverflow.com/a/21829819/320485仅适用于实现absolutedeviceorientation 事件(即 deviceorientation 的浏览器)alpha财产是compass面向)。这意味着目前提供的解决方案仅适用于 Android 浏览器,不适用于基于 iOS 的浏览器或任何其他不提供absolute基于设备方向的事件数据。

如今,要在 Android 和 iOS 浏览器上可靠地获取当前罗盘航向,您需要同时处理这两个问题absolute和非absolute提供额外的实现webkitCompassHeading属性,并确保将任何当前屏幕方向更改作为其中的一部分。 AFAIK 目前唯一执行此操作的库是全倾斜 JS https://github.com/richtr/Full-Tilt-JS(免责声明:我是这个库的作者)。

以下代码将为您提供跨 iOS 和 Android 浏览器的相同正确指南针方向,同时考虑到设备方向实现的差异并应用任何必要的运行时屏幕方向转换:

<!-- Include the Full Tilt JS library from https://github.com/richtr/Full-Tilt-JS -->
<script src="fulltilt-min.js"></script>

<script>

  // Obtain a new *world-oriented* Full Tilt JS DeviceOrientation Promise
  var promise = FULLTILT.getDeviceOrientation({ 'type': 'world' });

  // Wait for Promise result
  promise.then(function(deviceOrientation) { // Device Orientation Events are supported

    // Register a callback to run every time a new 
    // deviceorientation event is fired by the browser.
    deviceOrientation.listen(function() {

      // Get the current *screen-adjusted* device orientation angles
      var currentOrientation = deviceOrientation.getScreenAdjustedEuler();

      // Calculate the current compass heading that the user is 'looking at' (in degrees)
      var compassHeading = 360 - currentOrientation.alpha;

      // Do something with `compassHeading` here...

    });

  }).catch(function(errorMessage) { // Device Orientation Events are not supported

    console.log(errorMessage);

    // Implement some fallback controls here...

  });

</script>

这里有一个demo https://richtr.github.io/Marine-Compass/演示了这种获取用户所面对的罗盘航向的技术。它应该可以在 iOS 和 Android 浏览器上正常运行。

该演示中代码的实现如上所示,可以在 Github 上查看./scripts/compass.js:L268-L272 https://github.com/richtr/Marine-Compass/blob/15fd0a369faa9119f0f8133b2ceec74942be7bf1/scripts/compass.js#L268-L272.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我可以使用 Javascript 获取 iOS 和 Android 的指南针方向吗? 的相关文章

随机推荐