Search code examples
androidandroid-sensorsandroid-orientationcompass-geolocation

How type TYPE_ACCELEROMETER and TYPE_MAGNETIC_FIELD used to make compass on android devices


I am working on an application which uses compass although I successfully implemented it but there is no such brief explanation that how it works. Like how the TYPE_ACCELEROMETER and TYPE_MAGNETIC_FIELD was used to get the orientation. I know we did get it and the zero index of the array we got is the azimuth from which we get the degree and came to know where north is. But how it get to this all. Can anyone explain please?

Secondly what if I place my mobile on the floor suppose it points in the direction of north when it is placed on ground now I take up my mobile and hold I upside down what will happen and why?

According to my understanding the direction shouldn't changed. I might be wrong, can anyone please guide to me on this. Thanks a lot.


Solution

  • You need both the Magnectic field and Accelerometer to calculate the compass direction. You can see why if you read the source code of the getRotationMatrix or for a more verbose explanation see Convert magnetic field X, Y, Z values from device into global reference frame

    If you stand at the same place, the magnetic field does not change. That is the magnetic field vector returned in onSensorChanged should change very little. It is not the vector that change but the coordinates of the device that change. It is the meaning of what is being calculate and call the "compass direction" that confuses you. In this case the direction to be used as the "compass direction" is the direction of the y coordinate. Thus when you hold the phone vertically, the y coordinate points to the sky or the ground and it does not make sense to talk about "compass direction"