Search code examples
javascriptjqueryorientationdevice-orientationheading

Get horizontal heading from device orientation


I want to use the device orientation event to check the heading of the mobile device. This is what I do:

if (window.DeviceOrientationEvent) {
    window.addEventListener("deviceorientation", handleOrientation, false);
}
else{
    alert("Device Orientation is not available");
}

In my handleOrientation function I can have alpha, beta, gamma. But I want to have the heading of the device. When you lay down your device and do something like this:

enter image description here

function handleOrientation(orientData) {

    //var absolute = orientData.absolute;
    //var alpha = orientData.alpha;
    //var beta = orientData.beta;
    //var gamma = orientData.gamma;
}

How can I get the heading of the device from the values above?

Niels


Solution

  • You could use window.orientation, but pay attention: different devices returns different values.

    function handleOrientation() {
    
        switch(window.orientation)
        case 0:
         // do your stuff
         break;
        case -90
           ....
    }
    
    window.addEventListener('onorientationchange', handleOrientation);
    

    The iPhone has: ( from https://developer.apple.com/library/safari/#documentation/DataManagement/Reference/DOMWindowAdditionsReference/DOMWindowAdditions/DOMWindowAdditions.html )

    0 => Portrait orientation. This is the default value.

    -90 => Landscape orientation with the screen turned clockwise.

    90 => Landscape orientation with the screen turned counterclockwise.

    180 => Portrait orientation with the screen turned upside down. This value is currently not supported on iPhone.