Search code examples
javaandroidgeolocationangle

Angle between three geolocations


I need to calculate angle between three geolocations where two of them are always the same, and only one of them is changing(for example when user is walking).

enter image description here

First point is the starting position of user. Second point is the current position of user, so at the beginning first point equals second point. First point and fixed point are always same. I have latitude and longitude for each point.

I tried to use this formula:

double angle1 = Math.atan2(startingLocation.getLongitude() - destinationLocation.getLongitude(), startingLocation.getLatitude() - destinationLocation.getLatitude());
double angle2 = Math.atan2(currentLocation.getLongitude() - destinationLocation.getLongitude(), currentLocation.getLatitude() - destinationLocation.getLatitude());

return Math.toDegrees(angle1 - angle2);

But for example when first point == second point i except the degree to be 0. But it gives me strange results like 176 degrees. Where is the problem?


Solution

  • Angle Between Two Lines can be calculated by following function

    public static double angleBetween2Lines(Line2D line1, Line2D line2)
    {
        double angle1 = Math.atan2(line1.getY1() - line1.getY2(),
                               line1.getX1() - line1.getX2());
        double angle2 = Math.atan2(line2.getY1() - line2.getY2(),
                               line2.getX1() - line2.getX2());
        return angle1-angle2;
    }
    

    Source : Calculating the angle between two lines without having to calculate the slope? (Java)

    if your starting point is (x1,y1), end point is (x2,y2) and fixed point is (x3,y3) then you should use

    double angle1 = Math.atan2(y3-y1,x3-x1);
    double angle2 = Math.atan2(y3-y2,x3-x2);
    double result = angle1-angle2;