Bearing from one coordinate to another

后端 未结 4 1246
北恋
北恋 2020-12-08 21:33

I implemented the \"bearing\" formula from http://www.movable-type.co.uk/scripts/latlong.html. But it seems highly inaccurate - I suspect some mistakes in my implementation.

4条回答
  •  春和景丽
    2020-12-08 21:59

    A little bit cleaned up version of @IvanT answer:

    public static double bearingInRadians(LatLng src, LatLng dst) {
        double srcLat = Math.toRadians(src.getLatitude());
        double dstLat = Math.toRadians(dst.getLatitude());
        double dLng = Math.toRadians(dst.getLongitude() - src.getLongitude());
    
        return Math.atan2(Math.sin(dLng) * Math.cos(dstLat),
                Math.cos(srcLat) * Math.sin(dstLat) - 
                  Math.sin(srcLat) * Math.cos(dstLat) * Math.cos(dLng));
    }
    
    public static double bearingInDegrees(LatLng src, LatLng dst) {
        return Math.toDegrees((bearingInRadians(src, dst) + Math.PI) % Math.PI);
    }
    

    Where LatLng is:

    public final class LatLng {
        private final double latitude;
        private final double longitude;
    
        public LatLng(double latitude, double longitude) {
            this.latitude = latitude;
            this.longitude = longitude;
        }
    
        public double getLatitude() {
            return latitude;
        }
    
        public double getLongitude() {
            return longitude;
        }
    }
    

提交回复
热议问题