package com.hollywood.applet.utils;
|
|
import java.text.DecimalFormat;
|
|
public class DistanceCalculator {
|
public static void main(String[] args) {
|
String coord1 = "40.7128";
|
String coord2 = "-74.0060";
|
String coord3 = "34.0522";
|
String coord4 = "-118.2437";
|
|
double distance = calculateDistance(coord1, coord2, coord3, coord4);
|
DecimalFormat df = new DecimalFormat("#.##"); // 创建格式化对象,保留两位小数
|
String formattedDistance = df.format(distance); // 格式化距离
|
System.out.println("两个坐标点的距离为: " + formattedDistance + " km");
|
}
|
|
public static double calculateDistance(String lat1, String lon1, String lat2, String lon2) {
|
double lat1Double = Double.parseDouble(lat1);
|
double lon1Double = Double.parseDouble(lon1);
|
double lat2Double = Double.parseDouble(lat2);
|
double lon2Double = Double.parseDouble(lon2);
|
|
int R = 6371; // 地球半径,单位:km
|
double latDistance = Math.toRadians(lat2Double - lat1Double);
|
double lonDistance = Math.toRadians(lon2Double - lon1Double);
|
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
|
+ Math.cos(Math.toRadians(lat1Double)) * Math.cos(Math.toRadians(lat2Double))
|
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
|
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
double distanceInKm = R * c;
|
|
// 返回结果保留两位小数
|
String formattedDistance = String.format("%.2f", distanceInKm);
|
double roundedDistance = Math.round(distanceInKm * 100) / 100.0; // 四舍五入到两位小数
|
return roundedDistance;
|
}
|
}
|