如何将坐标放入Haversine算法?

时间:2017-06-01 19:39:30

标签: java geospatial

我不明白为什么我实施的Haversine公式的结果与计算距离的网站所计算的结果差别很大。

这是我的代码:

package wyjatki;

public class Coordinates {

    private double longitude, latitude;

    public Coordinates(double lon, double lat) {
        longitude = lon;
        latitude = lat;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }

    /**
     * 
     * @return REAL distance in kilometers to given coordinates. Uses
     *         Haversine algorithm
     * 
     */
    public double calculateHaversineDistance(Coordinates c) {

        double lon1, lon2, lat1, lat2, latRad1, latRad2, lonDelta, latDelta;
        final double R = 6371;

        lon1 = this.getLongitude();
        lon2 = c.getLongitude();
        lat1 = this.getLatitude();
        lat2 = c.getLatitude();

        latRad1 = Math.toRadians(lat1);
        latRad2 = Math.toRadians(lat2);

        lonDelta = Math.toRadians(lon2 - lon1);
        latDelta = Math.toRadians(lat2 - lat1);

        // Haversine algorithm
        double a = Math.sin(latDelta / 2) * Math.sin(latDelta / 2)
                + Math.cos(latRad1) * Math.cos(latRad2) * Math.sin(lonDelta / 2) * Math.sin(lonDelta / 2);
        double cc = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return R * cc;

    }

}
package wyjatki;

public class GoMain {

    public static void main(String[] args) {

        // Paris: // 48°51'24''N 2°21'07''E
        // Warsaw: // 52°14'N 21°1'E

        Coordinates Paris1  = new Coordinates(2.2107, 48.5124); 
        Coordinates Warszawa1  = new Coordinates(21.1, 52.14 ); 
        Coordinates Paris2  = new Coordinates( 2 + 21/60 + 7/6000, 48 + 51/60 + 24/6000); 
        Coordinates Warszawa2  = new Coordinates(21 + 10/60, 52 + 14/60 ); 

        // 1 try
        System.out.println("Paris - Warszawa: " + Math.round(Paris1.calculateHaversineDistance(Warszawa1)) + "km.");

        // 2 try (51' means minutes)
        System.out.println("Paris - Warszawa: " + Math.round(Paris2.calculateHaversineDistance(Warszawa2)) + "km.");

        // the correct answer is 1367km 
        // according to: https://www.distancecalculator.net/from-warsaw-to-paris

    }

}

使用我的代码我得到:1396km或1424km,核心答案是1367,根据https://www.distancecalculator.net/from-warsaw-to-paris

0 个答案:

没有答案