Search code examples
androidandroid-sensorsmagnetometer

Find heading for a device


I need to find the heading(in terms of degrees east or west of north) for an Android device that is being held vertically(like this: Heading) . I accessed the sensor.event[2] values returned from the geomagnetic sensor and found that they vary from 1 to 35 as I rotate the device completely about vertical axis. How can I convert this value to a heading? A very brief explanation or a link would be appreciated.


Solution

  • Look at SensorManager.getOrientation It returns 3 angles, around the 3 axes.

    Computes the device's orientation based on the rotation matrix.
    
    When it returns, the array values is filled with the result:
    
        values[0]: azimuth, rotation around the Z axis.
        values[1]: pitch, rotation around the X axis.
        values[2]: roll, rotation around the Y axis.
    
    The reference coordinate-system used is different from the world coordinate-system defined for the rotation matrix:
    
        X is defined as the vector product Y.Z (It is tangential to the ground at the device's current location and roughly points West).
        Y is tangential to the ground at the device's current location and points towards the magnetic North Pole.
        Z points towards the center of the Earth and is perpendicular to the ground.
    

    You'll need to use the geomagnetic and accelerometer sensors to feed in the data to get the rotation matrix. Look at SensorManager for more info