Take the 2-minute tour ×

I am trying to get the compass bearing in degrees (i.e. 0-360) using the following method:

float[] mGravity;
float[] mGeomagnetic;
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        mGravity = event.values;
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        mGeomagnetic = event.values;
    if (mGravity != null && mGeomagnetic != null) {
        float R[] = new float[9];
        float I[] = new float[9];
        boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
        if (success) {
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);
            float azimut = orientation[0];
            bearing.setText("Bearing: "+ azimut);

The azimuth value (i.e. orientation[0]) should be 0<=azimuth<360 but I am getting only values from -3 to 3 as I rotate my device. Can someone please tell me what the problem might be please?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

The values are in radian, you have to convert to degree

int azimut = (int) Math.round(Math.toDegrees(orientation[0]);
share|improve this answer
Thank you very much @Hoan Nguyen –  user1135357 Mar 1 '13 at 16:33
add comment

It is true that it is in Radians. Thanks Hoan. I added some logic to get that bearing in degrees from 0 to 360 becuase if I only converted it to degrees, I was getting values from -180 to 180.

float azimuthInRadians = orientation[0];
float azimuthInDegress = (float)Math.toDegrees(azimuthInRadians)+360)%360;
share|improve this answer
add comment

Your Answer


