javascriptmobilesensors

JS - Detect if a device is rotated more than a threshold degrees in one of the axes (X,Y,Z)


I've written the following JS to collect 10 device orientation data samples of each of the axes, using DeviceOrientationEvent:

    function addValue(arr,val){
      arr.push(val);
      if(arr.length > 10){
        //FIFO
        arr.shift();
      }
    }

    function checkMovement(){
        //TODO: Implement
    }

    function init() {
      let bufferA = [];
      let bufferB = [];
      let bufferG = [];
      window.addEventListener('deviceorientation', function(event) {
        addValue(bufferA,event.alpha);
        addValue(bufferB,event.beta);
        addValue(bufferG,event.gamma);
        console.log("Alpha:",bufferA);
        console.log("Beta:",bufferB);
        console.log("Gamma:",bufferG);
      });
    }

The code works and outputs as follow:

Alpha: (10) [270.1843934731245, 270.46643145307615, 270.5777617085752, 270.60145073101677, 270.6375654707842, 270.8057436294502, 270.8996987403409, 270.9120469572076, 270.6252518476537, 270.47210923234405]
Beta:  (10) [0.1752652827241338, 0.18823422659229486, 0.17726753978482904, 0.15365567314664708, 0.17945207160964366, 0.24686323651604228, 0.29261776755456925, 0.3637458880746612, 0.48965131703567966, 0.5984471316186161]
Gamma: (10) [0.04652736183550441, 0.04224191500987182, 0.04815352937436751, 0.16853189576371583, 0.32057100908945746, 0.2699882416274315, 0.1328731445658815, -0.22660041993990893, -0.48360428677544554, -0.5723959136181673]
...

Now I want to create a function that when invoked will look at the movement history (collected at the axes array) and will decide if the device rotated more then X deg in one of the axes.


Solution

  • Can you try this thing once.

    var previousOrientation = window.orientation;
    var checkOrientation = function(){
        if(window.orientation !== previousOrientation){
            previousOrientation = window.orientation;
            // orientation changed, do your magic here
        }
    };
    
    window.addEventListener("resize", checkOrientation, false);
    window.addEventListener("orientationchange", checkOrientation, false);
    
    // (optional) Android doesn't always fire orientationChange on 180 degree turns
    setInterval(checkOrientation, 2000);