Search code examples
javamathlatitude-longitudeangle

How to compute angle between two intersecting lines by having latitude/longitude points in Java?


I have three latitude/longitude points, P1, P2 and P3. They demonstrate two intersecting lines L1 and L2. P1 and P2 are at L1 and L2, respectively. P3 is the intersection point of the lines. It is easy to calculate the angle between the lines by having the given information in Euclidean space. However, points are in latitude/longitude format. So, how can I calculate the angle between the lines with Java? Thanks


Solution

  • You want to get angle between two bearings.

    Bearing at the Earth might be calculated using formula from latlong page

    Formula:    θ = atan2( sin Δλ ⋅ cos φ2 , cos φ1 ⋅ sin φ2 − sin φ1 ⋅ cos φ2 ⋅ cos Δλ )
    
    where   φ1,λ1 is the start point, φ2,λ2 the end point (Δλ is the difference in longitude)
    
    JavaScript:    (all angles     in radians)
    
    var y = Math.sin(λ2-λ1) * Math.cos(φ2);
    var x = Math.cos(φ1)*Math.sin(φ2) - Math.sin(φ1)*Math.cos(φ2)*Math.cos(λ2-λ1);
    var brng = Math.atan2(y, x).toDegrees();
    

    After finding bearings from P3 to P1 and from P3 to P2 (note that order is significant - P3P1 and P1P3 give different results) calculate difference.