Can I use Javascript to get the compass heading for iOS and Android?

前端 未结 3 1859
广开言路
广开言路 2020-11-30 04:32

Can I use Javascript in a cross-platform way to get the compass heading in iOS and Android (with Chrome), without using something like PhoneGap? I know iOS has DeviceOrienta

3条回答
  •  没有蜡笔的小新
    2020-11-30 04:45

    Yes you can! Unfortunately the alpha doesn't work on iPhones/iPads. With Mobile Safari, alpha is based on the direction the device was pointing when device orientation was first requested. The included webkit offers you the compass heading. To make it work for all other browsers (which all supports alpha as compassheading) you can use the following Javascript code:

    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 also supports Webkit, so would also use event.webkitCompassHeading, but that's OK.

    BTW: "oncompassneedscalibration" is also not supported for iPhones and iPads.

提交回复
热议问题