How to find the distance between two ZipCodes using Java Code?

前端 未结 5 1140
夕颜
夕颜 2020-12-10 05:15

My requirements are similar to this question, except the fact that I am prohibited to use the latitude and longitude values. I want to caluclate the \"walking\"

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 05:27

    If you're interested, here's my java implementation of the haversine formula

    /**
     * Calculates the distance in km between two lat/long points
     * using the haversine formula
     */
    public static double haversine(
            double lat1, double lng1, double lat2, double lng2) {
        int r = 6371; // average radius of the earth in km
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lng2 - lng1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
           Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) 
          * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = r * c;
        return d;
    }
    

    I hereby donate this to the public arena under GPL :)

提交回复
热议问题