JS HTML检测/获取Android的指南针



我正在建立基于Google Maps的网站,并且我正在尝试集成一个指南针(获取移动设备的标题),但问题是我只为iPhone获得绝对的标题,而Android总是让我相对朝着我加载页面的方向。

我如何获得相对于北方的Android标题?

现在是我的代码:

if (window.DeviceOrientationEvent && mobile) {
    window.addEventListener('deviceorientation', function(event) {
        var dir;
        if (event.webkitCompassHeading) {
            // Apple works only with this, alpha doesn't work
            dir = event.webkitCompassHeading + 180; 
        } else { 
            //tried also event.alpha...
            dir = event.absolute;
        }
        var arrowPath = {
            path: 'M -50 120 L 50 120 L 000 170 z',
            fillColor: black,
            fillOpacity: 1,
            scale: 0.1,
            strokeOpacity: 0,
            strokeColor: 'white',
            strokeWeight: 1,
            rotation: dir
        };
        userDirection.setIcon(arrowPath);
    });
}

正式,自2016年以来,Chrome的DeviceOrientationEvent不在支持绝对方向:

从Chrome 50开始,该学位包括默认情况下,deviceporientationEvent不再是绝对的到地球的坐标框架。这意味着只有在有实际的情况下才能触发deviceerientationEvents移动,通过设备加速度计的某种组合检测到和陀螺仪。磁力计和由于磁性引起的错误读数野外波动,不在图片中。

奇怪的是,实际上它确实适用于iPhone的Chrome ,您可以使用event.webkitCompassHeading 产生绝对方向,而在Android中,它相对在加载时相对于初始方向。

>

我的解决方案是使用 DeviceOrientationAbsolute(非标准和非预期):

if (isiOS) {
    window.addEventListener('deviceorientation', manageCompass)
} else if (isAndroid) {
    window.addEventListener("deviceorientationabsolute", manageCompass, true);
}
function manageCompass(event) {
    if (event.webkitCompassHeading) {
        absoluteHeading = event.webkitCompassHeading + 180;
    } else {
        absoluteHeading = 180 - event.alpha;
    }
    console.log(absoluteHeading);
}

另一个有用的答案(也适用于Web浏览器,不仅适用于Cordova)。

在此处检查(在移动中)

更新:

为了完整的清酒,从iOS13 开始,iPhone只需要在用户手势时就要求许可。iOS Android的完整代码:

在deviceready上 -

TrackOrientation() {
    // starts tracking on deviceready, updates value on currentCompass$ (fallback for ios13+ at "compassPremissioniOS13" funtion)
    if (typeof DeviceOrientationEvent['requestPermission'] !== 'function') {
      const deviceOrientationLestener = (event) => {
        if (this.globals.iphone) {
          this.currentCompass$.next(event['webkitCompassHeading']);
        } else {
          if (event.absolute) {
            this.currentCompass$.next(360 - event.alpha);
          } else {
            window.removeEventListener('deviceorientation', deviceOrientationLestener);
            window.addEventListener('deviceorientationabsolute', (eventB) => {
              this.currentCompass$.next(360 - eventB['alpha']);
            }, true);
          }
        }
      };
      window.addEventListener('deviceorientation', deviceOrientationLestener);
    } 
  }

用户手势 -

  compassPremissioniOS13$() {
    return new Promise((resolve, reject) => {
      if (navigator.geolocation) {
        if (typeof DeviceOrientationEvent['requestPermission'] === 'function') {
          DeviceOrientationEvent['requestPermission']()
            .then(permissionState => {
              if (permissionState === 'granted') {
                window.addEventListener('deviceorientation', (event) => {
                  this.currentCompass$.next(event['webkitCompassHeading']);
                });
                resolve('User accepted');
              } else {
                reject('User declined');
              }
            })
            .catch(console.error);
        }
      } else {
        alert('deviceorientation is not supported by this browser.');
        this.sendError('deviceorientation = null ("deviceorientation is not supported by this browser.")');
      }
    });
  }

现在,此选项在Android中不可用。等待下一个Android Update 8.0

最新更新