Java 后端代码:计算快递经纬度距离
Java 后端代码:计算快递经纬度距离
本代码使用 Java 实现计算两个经纬度坐标之间的距离,适用于快递配送、地图应用等场景。
package com.example.demo;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print('请输入快递起点经度:');
double startLongitude = scanner.nextDouble();
System.out.print('请输入快递起点纬度:');
double startLatitude = scanner.nextDouble();
System.out.print('请输入快递终点经度:');
double endLongitude = scanner.nextDouble();
System.out.print('请输入快递终点纬度:');
double endLatitude = scanner.nextDouble();
double distance = getDistance(startLongitude, startLatitude, endLongitude, endLatitude);
System.out.println('两点间距离为:' + distance + '米');
}
public static double getDistance(double startLongitude, double startLatitude, double endLongitude, double endLatitude) {
double earthRadius = 6371000;// 地球半径,单位为米
double radStartLongitude = Math.toRadians(startLongitude);
double radEndLongitude = Math.toRadians(endLongitude);
double radStartLatitude = Math.toRadians(startLatitude);
double radEndLatitude = Math.toRadians(endLatitude);
double a = Math.pow(Math.sin((radStartLatitude - radEndLatitude) / 2), 2) + Math.cos(radStartLatitude) * Math.cos(radEndLatitude) * Math.pow(Math.sin((radStartLongitude - radEndLongitude) / 2), 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = earthRadius * c;
return distance;
}
}
代码解释:
- 输入经纬度坐标: 代码使用
Scanner类从用户获取快递起点和终点的经纬度坐标。 - 计算距离:
getDistance方法利用 Haversine 公式计算两个经纬度坐标之间的距离,该公式考虑了地球的球面形状。 - 地球半径:
earthRadius定义了地球半径,单位为米。 - 弧度转换: 将经纬度坐标转换为弧度制,便于使用三角函数进行计算。
- Haversine 公式: Haversine 公式用于计算球面上两点之间的距离,公式中的
a表示两点之间的球面距离的平方,c表示两点之间的球面距离。 - 距离计算: 将
c与地球半径相乘得到两点之间的距离。
使用示例:
假设快递起点经纬度为 (116.404, 39.915),终点经纬度为 (121.473, 31.233),则程序执行后输出的结果为:
两点间距离为:1124008.782251753米
注意:
- 本代码使用的是地球半径的平均值,实际距离可能会有微小误差。
- 可以根据实际需求修改代码,例如添加单位转换、格式化输出等功能。
希望本代码能够帮助您完成相关任务。如有疑问,欢迎评论区留言讨论。
原文地址: https://www.cveoy.top/t/topic/mJcG 著作权归作者所有。请勿转载和采集!