Access device compass from webb app with Javascript

眉间皱痕 提交于 2019-12-10 21:19:09

问题


Is it possible to access the compass with Javascript on an iphone/ android device from a web app? Have been looking all over the net for hours I know you can access the accelerometer with

window.ondevicemotion = function(event)

Does anyone know if you can access the information from the compass??


回答1:


On iPhone, you can get the compass value like this.

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

Hope this help.




回答2:


It looks to be cross platform now, check this excellent article by Ruadhán O'Donoghue.

For Android, it still uses window.addEventListener('deviceorientation', ...) but check for other event properties (event.alpha which is compass orientation ; beta and gamma are also available, which represent the tilting).

Here are the relevant parts (adapted) if the link becomes unavailable:

   if(window.DeviceOrientationEvent) {
      window.addEventListener('deviceorientation', function(event) {
        var alpha;
        // Check for iOS property
        if(event.webkitCompassHeading) {
          alpha = event.webkitCompassHeading;
        }
        // non iOS
        else {
          alpha = event.alpha;
          if(!window.chrome) {
            // Assume Android stock
            alpha = alpha-270;
          }
        }
      }
    }

Another usage example is available on CodePen.



来源:https://stackoverflow.com/questions/5918982/access-device-compass-from-webb-app-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!