考虑到纬度和经度,我如何打印两个城市之间的距离

时间:2016-04-14 01:26:39

标签: java

我开始这样的程序:

with(res, Smooth(qlocations %mark% density)) 

我需要显示一个输出,提示用户输入两个城市和省名。它将在屏幕上打印一条消息,说明两个城市之间的距离,单位为公里。如果在文件中找不到其中一个城市,您将在屏幕上写一条错误消息,说明找不到哪个城市并默默结束该程序。如果用户输入相同的城市和省名称两次,那么您的程序应该做一些礼貌和明智的事情。有人可以帮我打印一些这段代码吗?谢谢。

1 个答案:

答案 0 :(得分:0)

来自https://www.geodatasource.com/developers/java

class DistanceCalculator
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "M") + " Miles\n");
        System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "K") + " Kilometers\n");
        System.out.println(distance(32.9697, -96.80322, 29.46786, -98.53506, "N") + " Nautical Miles\n");
    }

    private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
        double theta = lon1 - lon2;
        double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
        dist = Math.acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;
        if (unit == "K") {
            dist = dist * 1.609344;
        } else if (unit == "N") {
            dist = dist * 0.8684;
        }

        return (dist);
    }


    private static double deg2rad(double deg) {
        return (deg * Math.PI / 180.0);
    }


    private static double rad2deg(double rad) {
        return (rad * 180 / Math.PI);
    }
}