java - 给定经纬度坐标,如何打印两个城市之间的距离?

标签 java eclipse distance latitude-longitude

我的代码是这样开始的:

    public static void main(String[] args) {

//Intro 
    System.out.print("This program calculates the distance between two cities,     given their respective latitude and longitude points.");
    System.out.println();

//Get values for Latitude and Longitude
Scanner console = new Scanner(System.in);
    double lat1 = getCoordinates(" latitude 1: ", console); // Input lat1
    double long1 = getCoordinates(" longitude 1: ", console); // Input long1
    double lat2 = getCoordinates(" latitude 2: ", console); // Input lat2
    double long2 = getCoordinates(" longitude 2: ", console); // Input long2

public static double getCoordinates(String message, Scanner scan)
    {   
    System.out.print("Please enter" + message);
    int degrees = scan.nextInt();
    int minutes = scan.nextInt();
    return Math.toRadians(degrees + (minutes / 60.0));
    }

//Calculate Distance
public static double finalAnswer(double lat1, double long1, double lat2, double long2) {
double radiusOfEarth = 6372.795; //radius of Earth in km
double distance = Math.acos(Math.sin(lat1)*Math.sin(lat2) + 
                  Math.cos(lat1)*Math.cos(lat2) *
                  Math.cos(long2-long1)) * radiusOfEarth;

return distance;
System.out.print("The distance between the two cities is approximately " + distance + "km");

}
}

我需要能够为每个纬度和经度点输入度数和分钟(degrees, minutes)。但是,当我尝试在代码的最后一行打印“distance”时出现编译错误。另外,Eclipse 告诉我没有使用 lat1、long1、lat2 和 long2(“获取纬度和经度的值”部分)?有人可以帮我打印距离吗?谢谢。

最佳答案

在您的代码中:

..
return distance;
System.out.print("The distance between the two cities is approximately " 
    + distance + "km");
..

将此更改为:

..
System.out.print("The distance between the two cities is approximately " 
    + distance + "km");
return distance;
..

这是一个Haversine-formula implemented in Javascript来计算距离。 (应该很容易翻译成 Java。)

Formulas for calculating 'great circle' distances :

The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:

d=acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))

A mathematically equivalent formula, which is less subject to rounding error for short distances is:

d=2*asin(sqrt((sin((lat1-lat2)/2))^2 + cos(lat1)cos(lat2)(sin((lon1-lon2)/2))^2))

关于java - 给定经纬度坐标,如何打印两个城市之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13171791/

相关文章:

eclipse - 如何将 Xtext 与 Eclipse 插件集成?

javascript - 使用javascript计算经纬度之间的距离仅返回NaN

r - 测量每天第一个和最后一个位置记录与 R 中动物之间的距离

java - Spring Boot 中用户定义的休息端点

java - 等待执行者

java - 当发生 Java 错误时停止 AppleScript 运行 .jar

eclipse - 如何将Eclipse任务列表(Mylyn)连接到Google代码?

java - 它在 eclipse 的 tomcat servlet 中不起作用

java - 使用 SocketIO 的 Docker 容器之间无法建立连接

opencv - 使用立体相机到物体的距离