java 计算经纬度纬度之间的距离算法
时间: 2023-07-23 20:29:27 浏览: 147
以下是 Java 中使用 Haversine 公式计算经纬度之间距离的示例代码:
```
public class DistanceCalculator {
private static final double EARTH_RADIUS = 6371; // 地球平均半径,单位为千米
public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
double radLat1 = Math.toRadians(lat1);
double radLat2 = Math.toRadians(lat2);
double a = radLat1 - radLat2;
double b = Math.toRadians(lon1) - Math.toRadians(lon2);
double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b/2), 2))) * EARTH_RADIUS;
return distance;
}
}
```
其中,`lat1`、`lon1` 分别为第一个点的纬度和经度,`lat2`、`lon2` 分别为第二个点的纬度和经度,`distance` 单位为千米。
使用示例:
```
double distance = DistanceCalculator.calculateDistance(39.9, 116.3, 31.2, 121.5);
System.out.println("Distance: " + distance + " km");
```
输出结果为:
```
Distance: 1024.7060488391023 km
```
阅读全文