ali
ali

Reputation: 59

How to get angle from point1 to point2 in earth

I've spend much time internet for finding a way to do this. By exist documention I wrote below code, But it does not show correct angle. What's problem? enter image description here

private double angleFromCoordinate(double lat1, double long1, double lat2,
            double long2) {

        double dLon = (long2 - long1);

        double y = Math.sin(dLon) * Math.cos(lat2);
        double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
                * Math.cos(lat2) * Math.cos(dLon);

        double brng = Math.atan2(y, x);

        brng = Math.toDegrees(brng);

        brng %= 360;
        // brng = 360 - brng;

        return brng;
    }

UPDATED result of below code:

int angle = (int) angleFromCoordinate(36.288024, 59.615656
                    , 39.033659, 48.662504);
angle is '58'

Upvotes: 2

Views: 200

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79808

The methods Math.cos and Math.sin take a number of radians for their arguments. You are passing degrees into this method. You need to convert your degrees into radians at the start of the method.

private double angleFromCoordinate(double lat1, double long1, double lat2,
        double long2) {
    double lat1Rad = Math.toRadians(lat1);
    double long1Rad = Math.toRadians(long1);
    double lat2Rad = Math.toRadians(lat2);
    double long2Rad = Math.toRadians(long2);

then use the new variables lat1Rad and so on for the remaining mathematics.

Upvotes: 2

Related Questions