From d2660432ee1958228b4841c4e9f78901787ee258 Mon Sep 17 00:00:00 2001 From: wenc000 <450292408@qq.com> Date: Tue, 29 Oct 2019 23:44:07 +0800 Subject: [PATCH] =?UTF-8?q?PointUtil=E6=96=B0=E5=A2=9E=E7=BB=8F=E7=BA=AC?= =?UTF-8?q?=E5=BA=A6=E8=AE=A1=E7=AE=97=E8=B7=9D=E7=A6=BB=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/cm/common/utils/point/PointUtil.java | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/cloud-common/src/main/java/com/cm/common/utils/point/PointUtil.java b/cloud-common/src/main/java/com/cm/common/utils/point/PointUtil.java index 60cfc6a..6ee6418 100644 --- a/cloud-common/src/main/java/com/cm/common/utils/point/PointUtil.java +++ b/cloud-common/src/main/java/com/cm/common/utils/point/PointUtil.java @@ -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 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))); }