Closed davewang closed 8 months ago
private static CRSFactory crsFactory = new CRSFactory(); private static CoordinateReferenceSystem WGS84 = crsFactory.createFromName("epsg:4326"); private static CoordinateReferenceSystem UTM = crsFactory.createFromName("epsg:25833"); private static CoordinateTransformFactory ctFactory = new CoordinateTransformFactory(); private static CoordinateTransform wgsToUtm = ctFactory.createTransform(WGS84, UTM); public static Boolean pointInsidePolygonWithMargin(double lon, double lat,double margin, double[][] polygonPoints){ Coordinate[] polygonCoordinates = new Coordinate[polygonPoints.length+1]; for ( int i = 0 ; i < polygonPoints.length ; i++ ){ ProjCoordinate wtu = new ProjCoordinate(); wgsToUtm.transform(new ProjCoordinate(polygonPoints[i][0], polygonPoints[i][1]), wtu); polygonCoordinates[i] = new Coordinate(wtu.x,wtu.y); } //闭合 polygonCoordinates[polygonPoints.length] = polygonCoordinates[0]; ProjCoordinate current = new ProjCoordinate(); wgsToUtm.transform(new ProjCoordinate(lon, lat), current); // 创建多边形对象和当前位置对象 GeometryFactory geometryFactory = new GeometryFactory(); Polygon polygon = geometryFactory.createPolygon(polygonCoordinates); Point currentLocation = geometryFactory.createPoint(new Coordinate(current.x, current.y)); // 使用PreparedGeometryFactory提高计算性能 PreparedGeometryFactory preparedGeometryFactory = new PreparedGeometryFactory(); PreparedGeometry preparedPolygon = preparedGeometryFactory.create(polygon); boolean pointInsidePolygon = currentLocation.within(preparedPolygon.getGeometry()); if( pointInsidePolygon ){ // 创建STRtree空间索引 STRtree index = new STRtree(); for (int i = 0; i < polygonCoordinates.length - 1; i++) { Coordinate edgeStart = polygonCoordinates[i]; Coordinate edgeEnd = polygonCoordinates[i + 1]; LineString edge = geometryFactory.createLineString(new Coordinate[]{edgeStart, edgeEnd}); index.insert(edge.getEnvelopeInternal(), edge); } index.build(); // 计算点到多边形边界的最短距离 double shortestDistance = Double.POSITIVE_INFINITY; for (Object edgeObj : index.query(currentLocation.getEnvelopeInternal())) { LineString edge = (LineString) edgeObj; double distance = edge.distance(currentLocation); if (distance < shortestDistance) { shortestDistance = distance; } } System.out.println("当前位置到多边形边界的最短距离:" + shortestDistance + " meters ???"); return shortestDistance <= margin; }else{ return false; } } ` How to take distance transfrom to meters? UTM'unit is meters? Why is there a 4-meter discrepancy between my calculated result and the correct one?
This is outside the scope of JTS, which is a planar geometry library only.
The difference may be due to the difference in computation in a projected coordinate system versus treating geodetic as planar.