0
votes

I am trying to create an arrow that points towards a specific coordinate, like a compass. I am using Sensor.TYPE_ACCELEROMETER and Sensor.TYPE_MAGNETIC_FIELD from the phone to calculate the azimuth angle (I took reference from this question Using orientation sensor to point towards a specific location ):

       //calculate RotationMatrix
       if (gravity != null && geomag != null) {

           boolean success = SensorManager.getRotationMatrix(inR, I,
                                gravity, geomag);
              if (success) {
                SensorManager.getOrientation(inR, orientVals);
                azimuth = Math.toDegrees(orientVals[0]);
                pitch = Math.toDegrees(orientVals[1]);
                roll = Math.toDegrees(orientVals[2]);
              }
       }

        azimuth += geomagneticField.getDeclination();
        //azimuth = Math.round(sensorEvent.values[0]);
        float bearing = lastLocation.bearingTo(targetLocation);
        float angle = (float) azimuth + bearing;

I then use RotatateAnimation to create the Rotation of the arrow itself:

//the +90 below is because the ImageView arrow is pointing towards left by default 
RotateAnimation animation = new RotateAnimation(
                -(angle+90),
                -(angle+90),
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);

However, I tested four different targetLocations each in directions north east south and west, the arrow only correctly point towards the east west locations. In case of locations in direction north and south the arrow is rotated by 180 degrees, meaning that it will point completely towards the opposite direction. If I add 180 degrees to the rotation, the arrow will correctly point to the locations in north or south, but east and west locations will be wrong then. It is really frustrating and this makes absolutely no sense to me.

I would be really really thankful if someone could help me out here! Thanks in advance!

1

1 Answers

0
votes

I did some further tests and realized that the range from the bearing and the azimuth angles are each (0...180,-180...0) going clockwise and starting from 0, whereas the RotateAnimation takes angles from 0...360 clockwise. Therefore I just converted the azimuth and bearing angles by adding 360 if they were smaller than 0 before I proceeded in the calculations.