PointUtil新增经纬度计算距离方法

This commit is contained in:
wenc000 2019-10-29 23:44:07 +08:00
parent edca1adbd0
commit d2660432ee

View File

@ -1,6 +1,7 @@
package com.cm.common.utils.point;
import java.awt.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@ -16,6 +17,10 @@ import java.util.List;
**/
public class PointUtil {
private static final double EARTH_RADIUS = 637_1393.00D;
private static final double RADIAN = Math.PI / 180.00D;
private static final double HALF = 0.5D;
/**
* 点在多边形内
*
@ -133,6 +138,31 @@ public class PointUtil {
return s;
}
/**
* 计算距离Point的x为纬度y为经度
*
* @param point1
* @param point2
* @return
*/
public static double getDistance(Point point1, Point point2) {
double lat1 = point1.getX();
double lon1 = point1.getY();
double lat2 = point2.getX();
double lon2 = point2.getY();
double x, y, a, b, distance;
lat1 *= RADIAN;
lat2 *= RADIAN;
x = lat1 - lat2;
y = lon1 - lon2;
y *= RADIAN;
a = Math.sin(x * HALF);
b = Math.sin(y * HALF);
distance = EARTH_RADIUS * Math.asin(Math.sqrt(a * a + Math.cos(lat1) * Math.cos(lat2) * b * b)) / HALF;
return new BigDecimal(distance).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static void main(String[] args) {
Point point = new Point(111.770495, 40.871839);
List<Point> points = new ArrayList<>();
@ -141,7 +171,7 @@ public class PointUtil {
points.add(new Point(111.77202968235643, 40.86936472871906));
points.add(new Point(111.77072713936697, 40.87228340534707));
System.out.println(PointUtil.isPointInPoly(point, points));
System.out.println(PointUtil.getDistance(new Point(111.76776160830235, 40.87164162798379), new Point(111.76940775314925, 40.868854144474206)));
}