gpt4 book ai didi

javascript - 用JS计算智能手机的基本方向

转载 作者:行者123 更新时间:2023-12-04 10:11:01 27 4
gpt4 key购买 nike

在 JavaScript 中,我们可以获得设备的 alpha、beta 和 gamma Angular 。

  • alpha:绕 z 轴旋转 [0, 360]
  • beta:绕 x 轴旋转 [90, -90]
  • Gamma :绕 y 轴旋转 [180, -180]


  • window.addEventListener('deviceorientation', (event)=>{

    const alpha = event.alpha; // Returns the rotation of the device around the Z axis
    const beta = event.beta; // Returns the rotation of the device around the X axis; that is, the number of degrees, ranged between -180 and 180
    const gamma = event.gamma; // Returns the rotation of the device around the Y axis; that is, the number of degrees, ranged between -90 and 90

    console.log(`alpha: ${alpha}, beta: ${beta}, gamma: ${gamma}`);

    }, false);

    但是,我想使用这些 Angular 来确定设备的基本方向(北、西、东和南)。

    我的问题:
    是否可以仅使用 alpha Angular 来确定设备的基本方向,还是应该使用 beta 和 gamma?如果需要 beta 和 gamma;为了计算基本方向,我应该如何在计算中使用它们,有什么我应该知道的公式吗?

    最佳答案

    var heading;

    window.addEventListener('deviceorientation', handleOrientation, false);

    const handleOrientation = (event) => {
    if(event.webkitCompassHeading) {
    // some devices don't understand "alpha" (especially IOS devices)
    heading = event.webkitCompassHeading;
    }
    else{
    heading = compassHeading(event.alpha, event.beta, event.gamma);
    }
    };

    const compassHeading = (alpha, beta, gamma) => {

    // Convert degrees to radians
    const alphaRad = alpha * (Math.PI / 180);
    const betaRad = beta * (Math.PI / 180);
    const gammaRad = gamma * (Math.PI / 180);

    // Calculate equation components
    const cA = Math.cos(alphaRad);
    const sA = Math.sin(alphaRad);
    const cB = Math.cos(betaRad);
    const sB = Math.sin(betaRad);
    const cG = Math.cos(gammaRad);
    const sG = Math.sin(gammaRad);

    // Calculate A, B, C rotation components
    const rA = - cA * sG - sA * sB * cG;
    const rB = - sA * sG + cA * sB * cG;
    const rC = - cB * cG;

    // Calculate compass heading
    let compassHeading = Math.atan(rA / rB);

    // Convert from half unit circle to whole unit circle
    if(rB < 0) {
    compassHeading += Math.PI;
    }else if(rA < 0) {
    compassHeading += 2 * Math.PI;
    }

    // Convert radians to degrees
    compassHeading *= 180 / Math.PI;

    return compassHeading;
    };


    上面这段代码的灵感来自这些链接:
  • Calculate compass heading from DeviceOrientation Event API
  • Can I use Javascript to get the compass heading for iOS and Android?
  • https://www.w3.org/2008/geolocation/wiki/images/e/e0/Device_Orientation_%27alpha%27_Calibration-_Implementation_Status_and_Challenges.pdf
  • https://w3c.github.io/deviceorientation/spec-source-orientation.html#worked-example
  • 关于javascript - 用JS计算智能手机的基本方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61336948/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com