开发者

Access device compass from web app with Javascript

Is it possi开发者_开发问答ble 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??


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

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

Hope this help.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜