Search code examples
cordovaphonegap-plugins

Phonegap - Device Orientation in degrees & Magnetic Field


Can anyone tell me whether it is possible though Phonegap to get Android Device Orientation in degrees (angle of the phone relative to the ground)? Also, is it possible to get the Magnetic Field as well?


Solution

  • PhoneGap Docs

    The compass is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99.

    The compass heading information is returned via a CompassHeading object using the compassSuccess callback function.

    function onSuccess(heading) {
        alert('Heading: ' + heading.magneticHeading);
    };
    
    function onError(error) {
        alert('CompassError: ' + error.code);
    };
    
    navigator.compass.getCurrentHeading(onSuccess, onError);
    

    If you want to access the rotation-degrees of the x,y or z axis of the Phone you can simply use bare HTML5. Here is a great article about it: THIS END UP: USING DEVICE ORIENTATION

    Code example:

      window.addEventListener('deviceorientation', function(eventData) {
    // gamma is the left-to-right tilt in degrees, where right is positive
    var tiltLR = eventData.gamma;
    
    // beta is the front-to-back tilt in degrees, where front is positive
    var tiltFB = eventData.beta;
    
    // alpha is the compass direction the device is facing in degrees
    var dir = eventData.alpha
    
    // deviceorientation does not provide this data
    var motUD = null;
    
    // call our orientation event handler
    deviceOrientationHandler(tiltLR, tiltFB, dir, motUD);
    }, false);
    

    example