行业知识
Java中使用JTS对空间几何计算(距离、点在面内、长度、面积、相交等)模拟的大概写法
场景
基于GIS相关的集成系统,需要对空间数据做一些判断处理。比如读取WKT数据、点到点、点到线、点到面的距离,
线的长度、面的面积、点是否在面内等处理。
JTS
(Java Topology Suite) Java拓扑套件,是Java的处理地理数据的API。
github地址:
https://github.com/locationtech/jts
API文档地址:
https://locationtech.github.io/jts/javadoc/
Maven中央仓库地址:
https://mvnrepository.com/artifact/org.locationtech.jts/jts-core
org.locationtech.jts jts-core 1.18.2
特点
实现了OGC关于简单要素SQL查询规范定义的空间数据模型
一个完整的、一致的、基本的二维空间算法的实现,包括二元运算(例如touch和overlap)和空间分析方法(例如intersection和buffer)
一个显示的精确模型,用算法优雅的解决导致dimensional collapse(尺度坍塌–专业名词不知道对不对,暂时这样译)的情况。
健壮的实现了关键计算几何操作
提供著名文本格式的I/O接口
JTS是完全100%由Java写的
JTS支持一套完整的二元谓词操作。二元谓词方法将两个几何图形作为参数,
返回一个布尔值来表示几何图形是否有指定的空间关系。它支持的空间关系有:
相等(equals)、分离(disjoint)、相交(intersect)、相接(touches)、
交叉(crosses)、包含于(within)、包含(contains)、覆盖/覆盖于(overlaps)。
同时,也支持一般的关系(relate)操作符。
relate可以被用来确定维度扩展的九交模型(DE-9IM),它可以完全的描述两个几何图形的关系。
常用方法
Geometry方法// 空间判断// 不相交boolean disjoint = geometry.disjoint(geometry2);// 相交boolean intersects = geometry.intersects(geometry2);// 相切,内部不相交boolean touches = geometry.touches(geometry2);// 被包含boolean within = geometry.within(geometry2);//包含,只针对几何内部而言,不计算边界boolean contains = geometry.contains(geometry2);//覆盖,不区分集合边界与内部boolean covers = geometry.covers(geometry);//相交,不能是相切或者包含boolean crosses = geometry.crosses(geometry);//相交boolean overlaps = geometry.overlaps(geometry2);// 两个几何的空间关系IntersectionMatrix relate1 = geometry.relate(geometry2);//空间计算//求交集Geometry intersection = geometry.intersection(geometry2);//求并集Geometry union = geometry.union(geometry);//geometry-交集Geometry difference = geometry.difference(geometry2);// 并集-交集Geometry symDifference = geometry.symDifference(geometry);// 几何缓冲生成新几何,单位与geometry坐标系一致Geometry buffer1 = geometry.buffer(2);// 生成包含几何的最小凸多边形Geometry convexHull = geometry.convexHull();// 两个几何的最小距离double distance = geometry.distance(geometry);// 面积double area = geometry.getArea();//几何类型String geometryType = geometry.getGeometryType();// 边界Geometry boundary = geometry.getBoundary();// 获取中心点Point centroid = geometry.getCentroid();
使用工具代码:
1.放在前面转gps的经纬度:Geometry 转gps的经纬度·
Geometry 结果不是正常的经纬度需要写函数转移gps正常的经纬度
public static void main() throws Exception { // 输入坐标系 String fromCRS = "EPSG:4326"; // WGS 84 经纬度坐标系 // 输出坐标系 String toCRS = "EPSG:3857"; // Web Mercator 投影坐标系 // 准备坐标数据 Coordinate lonLatCoord = new Coordinate(104.06584, 30.65943); // 经度、纬度 GeometryFactory geomFactory = new GeometryFactory(); Geometry pointGeom = geomFactory.createPoint(lonLatCoord); // 获取转换器 CoordinateReferenceSystem fromCRSys = CRS.decode(fromCRS); CoordinateReferenceSystem toCRSys = CRS.decode(toCRS); MathTransform transform = CRS.findMathTransform(fromCRSys, toCRSys); // 坐标系转换 Geometry transformedGeom = JTS.transform(pointGeom, transform); // 输出结果 Coordinate tranCoord = transformedGeom.getCoordinate(); System.out.println("x: " + tranCoord.x + ", y: " + tranCoord.y); } 2.创建点、线
//创建点 Point point = new GeometryFactory().createPoint(new Coordinate(1, 1)); // create a geometry by specifying the coordinates directly //通过指定坐标创建线 Coordinate[] coordinates = new Coordinate[]{new Coordinate(0, 0), new Coordinate(10, 10), new Coordinate(20, 20)}; // use the default factory, which gives full double-precision Geometry g2 = new GeometryFactory().createLineString(coordinates); //System.out.println("Geometry 2: " + g2); //输出结果:Geometry 2: LINESTRING (0 0, 10 10, 20 20) 3.计算点是否在线上、点是否在面内
//创建点 Point point = new GeometryFactory().createPoint(new Coordinate(1, 1)); //输出结果:POINT (1 1) //计算点是否在线上 //System.out.println(g1.contains(point)); //输出结果:true //计算点是否在面内 Point point2 = new GeometryFactory().createPoint(new Coordinate(70, 70)); //System.out.println(g1.contains(point2)); //输出结果: true Point point3 = new GeometryFactory().createPoint(new Coordinate(20, 10)); //System.out.println(g1.contains(point3)); //输出结果: false
4.计算两个几何图形的交点
// compute the intersection of the two geometries //计算两个几何图形的交点 Geometry g3 = g1.intersection(g2); //System.out.println("G1 intersection G2: " + g3); //输出结果:G1 intersection G2: MULTILINESTRING ((0 0, 10 10), (10 10, 20 20)) 5.创建一个多点
// create a factory using default values (e.g. floating precision) //创建一个MultiPoint多点 GeometryFactory fact = new GeometryFactory(); // Point p1 = fact.createPoint(new Coordinate(0,0));// System.out.println(p1);//// Point p2 = fact.createPoint(new Coordinate(1,1));// System.out.println(p2);//// MultiPoint mpt = fact.createMultiPointFromCoords(new Coordinate[] { new Coordinate(0,0), new Coordinate(1,1) } );// System.out.println(mpt); //输出结果:// POINT (0 0)// POINT (1 1)// MULTIPOINT ((0 0), (1 1)) 6.创建闭合线-多边形
//创建闭合线-LinearRing LinearRing lr = new GeometryFactory().createLinearRing(new Coordinate[]{new Coordinate(0, 0), new Coordinate(0, 10), new Coordinate(10, 10), new Coordinate(10, 0), new Coordinate(0, 0)}); //System.out.println(lr); //输出结果:LINEARRING (0 0, 0 10, 10 10, 10 0, 0 0) 7.创建几何集合列表
//创建几何集合列表 Geometry[] garray = new Geometry[]{g1,g2}; GeometryCollection gc = fact.createGeometryCollection(garray); //System.out.println(gc.toString()); //输出结果:GEOMETRYCOLLECTION (POLYGON ((40 100, 40 20, 120 20, 120 100, 40 100)), LINESTRING (0 0, 10 10, 20 20)) 8.几何关系判断-交集-差集-并集-相对差集
//准备数据操作-Coordinate[] coords1对象获取:public static void main() { // 假设你有一组经纬度点集合,存储在一个二维数组中 double[][] latLngPoints = { {latitude1, longitude1}, {latitude2, longitude2}, // 继续添加经纬度点的坐标 }; // 创建一个 Coordinate 对象数组 Coordinate[] coordinates = new Coordinate[latLngPoints.length]; for (int i = 0; i 8.1 合并两个多边形-并集-union
图中画红色斜线的区域----------------a区域b区域ab区域的总面积就是并集
说明: union操作就是上图中将A和B合成了为-绿色-框选部分的新的多边形
// 创建一个GeometryFactory实例 GeometryFactory geometryFactory = new GeometryFactory(); // 定义两个多边形的坐标点 Coordinate[] coords1 = { /* 第一个多边形的坐标点 */ }; Coordinate[] coords2 = { /* 第二个多边形的坐标点 */ }; // 使用坐标点创建两个多边形 Polygon polygon1 = geometryFactory.createPolygon(coords1); Polygon polygon2 = geometryFactory.createPolygon(coords2); // 使用union方法合并两个多边形 Geometry union = polygon1.union(polygon2); //可以设置一个初始化,以此来合并多个多边形,不存在交集的Geometry不会合并会独立返回 union = polygon1.union(polygon3); union = polygon1.union(polygon4); // 输出合并后的多边形或进行其他操作... System.out.println("Merged Geometry: " + union); System.out.println("合并完还剩下几个多边形: " + union.size); 8.2 两个多边形-交集-intersection
图中画红色斜线的区域-ab区域-就是交集
// 创建一个GeometryFactory实例,用于创建几何对象 GeometryFactory geometryFactory = new GeometryFactory(); // 定义两个多边形的坐标点(这里只是示例,你需要根据实际情况提供坐标点) Coordinate[] coords1 = { /* 第一个多边形的坐标点 */ }; Coordinate[] coords2 = { /* 第二个多边形的坐标点 */ }; // 使用坐标点创建两个多边形对象 Polygon polygon1 = geometryFactory.createPolygon(coords1); Polygon polygon2 = geometryFactory.createPolygon(coords2); // 计算两个多边形的交集 Geometry intersection = polygon1.intersection(polygon2); // 输出交集的几何类型和坐标点(如果需要的话) System.out.println("Intersection geometry type: " + intersection.getGeometryType()); // 如果需要,你可以进一步处理或输出交集的坐标点等信息。 8.3 两个多边形-差集-difference
图中画红色斜线的区域-A.difference(B) 将返回一个只包含 A 中矩形 B 外部部分的几何体
8.4 两个多边形-相对差集-对称差-symDifference
图中画红色斜线的区域-A.symDifference(B) 将返回一个包含 A 和 B 中各自不同的部分的几何体。
GeometryFactory geometryFactory = new GeometryFactory(); // 定义两个多边形的坐标点(这里只是示例,你需要根据实际情况提供坐标点) Coordinate[] coords1 = { /* 第一个多边形的坐标点 */ }; Coordinate[] coords2 = { /* 第二个多边形的坐标点 */ }; // 使用坐标点创建两个多边形对象 Polygon polygon1 = geometryFactory.createPolygon(coords1); Polygon polygon2 = geometryFactory.createPolygon(coords2); //计算a相对于b的对称差Geometry symDifference = a.symDifference(b); 9.计算距离
//计算距离distance Point p1 = fact.createPoint(new Coordinate(0,0)); //System.out.println(p1); Point p2 = fact.createPoint(new Coordinate(3,4)); ///System.out.println(p2); //System.out.println(p1.distance(p2)); //输出结果// POINT (0 0)// POINT (3 4)// 5.0
10.计算长度和面积
//计算距离distance Point p1 = fact.createPoint(new Coordinate(0,0)); //System.out.println(p1); Point p2 = fact.createPoint(new Coordinate(3,4)); ///System.out.println(p2); //System.out.println(p1.distance(p2)); //输出结果// POINT (0 0)// POINT (3 4)// 5.0
11.求点到线、点到面的最近距离
Geometry g5 = null; Geometry g6 = null; try { //读取面 g5 = new WKTReader().read("POLYGON((40 100, 40 20, 120 20, 120 100, 40 100))"); g6 = new WKTReader().read("LINESTRING(0 0, 0 2)"); //计算面积getArea() //System.out.println(g5.getArea()); //输出结果:6400.0 //计算长度getLength() //System.out.println(g6.getLength()); //输出结果:2.0 } catch (ParseException e) { e.printStackTrace(); } 12.求点到线、点到面的最近距离
GeometryFactory gf = new GeometryFactory(); WKTReader reader2 = new WKTReader(gf); Geometry line2 = null; Geometry g7 = null; try { line2 = reader2.read("LINESTRING(0 0, 10 0, 10 10, 20 10)"); g7 = new WKTReader().read("POLYGON((40 100, 40 20, 120 20, 120 100, 40 100))"); } catch (ParseException e) { e.printStackTrace(); } Coordinate c = new Coordinate(5, 5); PointPairDistance ppd = new PointPairDistance(); //求点到线的最近距离 //DistanceToPoint.computeDistance(line2,c,ppd); //输出结果:5.0 //求点到面的最近距离 DistanceToPoint.computeDistance(g7,c,ppd); System.out.println(ppd.getDistance()); //输出结果38.07886552931954 13.创建圆形
import com.vividsolutions.jts.geom.*;import com.vividsolutions.jts.util.GeometricShapeFactory; /** * 根据圆形中心点经纬度、半径生成圆形(类圆形,32边多边形) * @param x 中心点经度 * @param y 中心点纬度 * @param radius 半径(米) * @return */ public static Polygon createCircle(double x, double y, final double radius) { //将半径转换为度数 double radiusDegree = parseYLengthToDegree(radius); //生成工厂类private static GeometricShapeFactory shapeFactory = new GeometricShapeFactory();//设置生成的类圆形边数 shapeFactory.setNumPoints(32); //设置圆形中心点经纬度 shapeFactory.setCentre(new Coordinate(x, y)); //设置圆形直径 shapeFactory.setSize(radiusDegree * 2); //使用工厂类生成圆形 Polygon circle = shapeFactory.createCircle(); return circle; } 14.创建椭圆
/** * 根据中心点经纬度、长轴、短轴、角度生成椭圆 * @param x * @param y * @param macroaxis * @param brachyaxis * @param direction * @return */ public static Polygon createEllipse(double x,double y,double macroaxis,double brachyaxis,double direction){ //将长短轴转换为度数 double macroaxisDegree = parseYLengthToDegree(macroaxis); double brachyaxisDegree = parseYLengthToDegree(brachyaxis); //将夹角转换为弧度 double radians = Math.toRadians(direction); //设置中心点 shapeFactory.setCentre(new Coordinate(x,y)); //设置长轴长度 shapeFactory.setWidth(macroaxisDegree); //设置短轴长度 shapeFactory.setHeight(brachyaxisDegree); //设置长轴和X轴夹角 shapeFactory.setRotation(radians); //生成椭圆对象 Polygon ellipse = shapeFactory.createEllipse(); return ellipse; } 15.创建圆扇形
/** * 根据中心点经纬度、半径、起止角度生成扇形 * @param x 经度 * @param y 纬度 * @param radius 半径(公里) * @param bAngle 起始角度(X轴正方向为0度,逆时针旋转) * @param eAngle 终止角度 * @param pointsNum 点数(往上参考可以给32) * @return */ public static Polygon createSector(double x,double y,double radius,double bAngle,double eAngle,int pointsNum){ //将半径转换为度数 double radiusDegree = parseYLengthToDegree(radius); //将起始角度转换为弧度 double bAngleRadian = Math.toRadians(bAngle); //将终止角度-起始角度计算扇形夹角 double angleRadian = Math.toRadians((eAngle - bAngle + 360) % 360); //设置点数 shapeFactory.setNumPoints(pointsNum); //设置中心点经纬度 shapeFactory.setCentre(new Coordinate(x, y)); //设置直径 shapeFactory.setSize(radiusDegree * 2); //传入起始角度和扇形夹角,生成扇形 Polygon sector = shapeFactory.createArcPolygon(bAngleRadian,angleRadian); return sector; }