在实际开发中,计算两点距离的应用场景有很多,比如,钉钉的打卡功能,超过距离不允许打卡。
经纬度实体类
/**
*Data是lombok的注解,提供类的get、set、equals、hashCode、toString等方法
*/
@Data
public class MapPoint {
/**
* 纬度
*/
private Double latitude;
/**
* 经度
*/
private Double longitude;
}
计算距离
public static Double getDisdance(MapPoint point1, MapPoint point2) {
double lat1 = (point1.getLatitude() * Math.PI) / 180; //将角度换算为弧度
double lat2 = (point2.getLatitude() * Math.PI) / 180; //将角度换算为弧度
double latDifference = lat1 - lat2;
double lonDifference = (point1.getLongitude() * Math.PI) / 180 - (point2.getLongitude() * Math.PI) / 180;
//计算两点之间距离 6378137.0 取自WGS84标准参考椭球中的地球长半径(单位:m)
return 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(latDifference / 2), 2)
+ Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(lonDifference / 2), 2)))* 6378137.0;
}
测试
public static void main(String[] args) {
MapPoint mapPoint1 = new MapPoint();
mapPoint1.setLongitude(121.43596);
mapPoint1.setLatitude(31.15956);
MapPoint mapPoint2 = new MapPoint();
mapPoint2.setLongitude(121.46184);
mapPoint2.setLatitude(31.25551);
Double aDouble = getDistance(mapPoint1, mapPoint2);
System.out.println("距离是:" + aDouble);
}
运行结果:距离是:10961.64292265375