<!-- JTS库几何计算 -->
<dependency>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>1.18.1</version>
</dependency>
public class MapUtil {
private static final double x_PI = (3.14159265358979324 * 3000.0) / 180.0;
private static final double PI = 3.1415926535897932384626;
private static final double a = 6378245.0;
private static final double ee = 0.00669342162296594323;
public static double[] wgs84togcj02(double lng,double lat) {
double dlat = transformlat(lng - 105.0, lat - 35.0);
double dlng = transformlng(lng - 105.0, lat - 35.0);
double radlat = (lat / 180.0) * PI;
double magic = Math.sin(radlat);
magic = 1 - ee * magic * magic;
double sqrtmagic = Math.sqrt(magic);
dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI);
dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI);
double mglat = lat + dlat;
double mglng = lng + dlng;
double[] result = new double[2];
result[0] = mglng;
result[1] = mglat;
return result;
}
public static double transformlat(double lng, double lat) {
double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat
+ 0.2 * Math.sqrt(Math.abs(lng));
ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0;
ret += ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) / 3.0;
ret += ((160.0 * Math.sin((lat / 12.0) * PI) + 320 * Math.sin((lat * PI) / 30.0)) * 2.0) / 3.0;
return ret;
}
public static double transformlng(double lng, double lat) {
double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0;
ret += ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) / 3.0;
ret += ((150.0 * Math.sin((lng / 12.0) * PI) + 300.0 * Math.sin((lng / 30.0) * PI)) * 2.0) / 3.0;
return ret;
}
public static boolean pointInPolygon(double lng,double lat) {
// 创建GeometryFactory对象
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4326);
//创建多边形
Coordinate[] polygonCoords = new Coordinate[] {
new Coordinate(-73.987, 40.749),
new Coordinate(-73.986, 40.749),
new Coordinate(-73.986, 40.748),
new Coordinate(-73.987, 40.748),
new Coordinate(-73.987, 40.749)
};
LinearRing linearRing = geometryFactory.createLinearRing(polygonCoords);
Polygon polygon = geometryFactory.createPolygon(linearRing, null);
// 创建要判断的点
Coordinate pointCoord = new Coordinate(lng, lat);
// 判断点是否在多边形内
boolean isInside = CGAlgorithms.isPointInRing(pointCoord, polygon.getExteriorRing().getCoordinates());
return isInside;
}
}