我的代码是这样开始的:
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/