Search code examples
javascriptiphonewebkitdevice-orientation

How to get device rotation for iPhone 7 in javascript?


I want to get the device rotation for (alpha, beta, gamma) for iPhone 7 and higher. For iPhone 6 this works well for me:

window.addEventListener('deviceorientation', function(event) {
  console.log(event.alpha);
  console.log(event.beta);
  console.log(event.gamma);
});

But for iPhone > 6 this event is not triggered anymore. To be clear, i dont want the device orientation (portrait/landscape), I want the rotation. Best case would be absoulte (calibrated) data.

For Android "deviceorientationabsolute" works well. Is there something similar for the Apple universe?

Thanks & regards, Andreas


Solution

  • Ok, the solution for me was to get the user permission to use orientation like this. After that 'ondeviceorientation' works.

    function startOrientation() {
      if (typeof DeviceMotionEvent.requestPermission === 'function') {
        DeviceOrientationEvent.requestPermission().then(function(response) {
          if (response == 'granted') {
            console.log('granted');
          }
        });
      } else {
        console.log('not granted');
      }
    }
    
    $("#get_permission").click(function(){
      startOrientation();
    });