package com.dji.sample.territory.utils; import org.geotools.geometry.jts.JTS; import org.geotools.referencing.CRS; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CRSAuthorityFactory; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Point; public class CoordinateSystemUtil { public static Geometry pointCGCStoWGS(Double lot, Double lat) { String wkt = "POINT (" + lot + " " + lat + ")"; Geometry source = createGeometry(wkt, 4527); return coordinateTransform(source, 4326); } public static Geometry pointWGStoCGCS(Double lot, Double lat) { String wkt = "POINT (" + lot + " " + lat + ")"; Geometry source = createGeometry(wkt, 4326); return coordinateTransform(source, 4527); } public static String poylonWGStoCGCS(String poylon) { Geometry source = createGeometry(poylon, 4326); Geometry transformedGeometry = coordinateTransform(source, 4527); return transformedGeometry.toText(); } public static String poylonCGCStoWGS(String poylon) { Geometry source = createGeometry(poylon, 4527); Geometry transformedGeometry = coordinateTransform(source, 4326); return transformedGeometry.toText(); } public static double[] extractCoordinates(Geometry geometry) { // 如果是点类型的几何对象,则直接提取坐标 if (geometry instanceof Point) { Coordinate coordinate = geometry.getCoordinate(); return new double[]{coordinate.getX(), coordinate.getY()}; } else { // 如果不是点类型,则返回 null 或者根据需要处理其他几何对象类型 return null; } } // 格式化坐标值,保留指定小数位数 public static String formatCoordinate(double coordinate) { return String.format("%.15f", coordinate).replaceAll("\\.?0*$", ""); } public static Geometry createGeometry(String wkt, int srid) { try { WKTReader reader = new WKTReader(); Geometry geometry = reader.read(wkt); geometry.setSRID(srid); return geometry; } catch (ParseException e) { System.out.println("WKT解析错误: " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } public static Geometry coordinateTransform(Geometry sourceGeometry, int targetSrid) { if (sourceGeometry == null || sourceGeometry.getSRID() == 0 || targetSrid == 0) { return null; } try { CRSAuthorityFactory factory = CRS.getAuthorityFactory(true); CoordinateReferenceSystem source = factory.createCoordinateReferenceSystem("EPSG:" + sourceGeometry.getSRID()); CoordinateReferenceSystem target = factory.createCoordinateReferenceSystem("EPSG:" + targetSrid); MathTransform transform = CRS.findMathTransform(source, target, true); Geometry res = JTS.transform(sourceGeometry, transform); if (res != null) { res.setSRID(targetSrid); } return res; } catch (FactoryException | TransformException e) { e.printStackTrace(); } return null; } }