14

我可以在不使用 PhoneGap 之类的东西的情况下以跨平台方式使用 Javascript 在 iOS 和 Android(使用 Chrome)中获取指南针方向吗?我知道 iOS 有DeviceOrientationEvent,但我在 Chrome for Android 上找不到任何等价物。

4

3 回答 3

21

作为入门,您应该查看之前的相关 StackOverflow 答案,并熟悉在 Web 应用程序中使用 DeviceOrientation 事件的一般实际注意事项。

我在之前的相关 StackOverflow 答案中提供的简单解决方案仅适用于实现absolutedeviceorientation 事件的浏览器(即 deviceorientationalpha属性面向compass的浏览器)。这意味着那里提供的解决方案目前仅适用于 Android 浏览器,而不适用于基于 iOS 的浏览器或任何其他不提供absolute-based deviceorientation 事件数据的浏览器。

为了在今天的 Android 和 iOS 浏览器中可靠地获取当前指南针方向,您需要处理提供附加属性的两种实现absolute和非absolute实现,webkitCompassHeading并确保将任何当前屏幕方向更改作为其中的一部分。AFAIK 目前唯一这样做的库是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>

这是一个演示,演示了这种技术来获取用户所面对的罗盘方向。它应该适用于 iOS 和 Android 浏览器。

该演示中的代码实现如上所示,可以在 Github 上的./scripts/compass.js:L268-L272查看。

于 2014-10-09T10:16:31.307 回答
8

是的你可以!不幸的是,alpha这不适用于 iPhone/iPad。使用 Mobile Safari,alpha基于首次请求设备方向时设备指向的方向。包含的 webkit 为您提供指南针方向。要使其适用于所有其他浏览器(都支持alphaas compassheading),您可以使用以下 Javascript 代码:

if (window.DeviceOrientationEvent) {
  // Listen for the deviceorientation event and handle the raw data
  window.addEventListener('deviceorientation', function(eventData) {
    var compassdir;

    if(event.webkitCompassHeading) {
      // Apple works only with this, alpha doesn't work
      compassdir = event.webkitCompassHeading;  
    }
    else compassdir = event.alpha;
  });
}

Android 也支持 Webkit,所以也会使用 event.webkitCompassHeading,不过没关系。

顺便说一句:oncompassneedscalibrationiPhone 和 iPad 也不支持“”。

于 2014-12-09T22:51:53.850 回答
-6

我相信您可以使用来自 navigator.geolocation 的位置对象的“标题”字段,请参见此处:

https://developer.mozilla.org/en-US/docs/WebAPI/Using_geolocation

我不知道别的办法。

希望有帮助,A.

于 2013-04-16T22:51:05.393 回答