How to get Direction in Android (Such as North, West)

Cemal Inanc picture Cemal Inanc · Nov 29, 2011 · Viewed 20.4k times · Source

I am new in Android and I want to get direction according to my camera. How can I get direction information according to my camera? Could you give an idea for this?

Answer

Yves M. picture Yves M. · Apr 14, 2014

TYPE_ORIENTATION is deprecated

We cannot use the Orientation Sensor anymore, we can use the Magnetic Field Sensor and Accelerometer Sensors in tandem to get equivalent functionality. It's more work but it does allow to continue to use a callback to handle orientation changes.

Here is a compass sample : http://www.codingforandroid.com/2011/01/using-orientation-sensors-simple.html

Conversion from accelerometer and magnetic field to azimut :

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];

        if (SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic)) {

            // orientation contains azimut, pitch and roll
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);

            azimut = orientation[0];
        }
    }
}

To point the north you can calculate a rotation in degrees :

float rotation = -azimut * 360 / (2 * 3.14159f);