Java中使用JTS对空间几何计算(距离、点在面内、长度、面积、相交等)模拟的大概写法

本文主要是介绍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

  <!-- https://mvnrepository.com/artifact/org.locationtech.jts/jts-core --><dependency><groupId>org.locationtech.jts</groupId><artifactId>jts-core</artifactId><version>1.18.2</version></dependency>

特点

实现了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-precisionGeometry 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));//输出结果: truePoint 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.创建闭合线-多边形

        //创建闭合线-LinearRingLinearRing 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 < latLngPoints.length; i++) {double latitude = latLngPoints[i][0];double longitude = latLngPoints[i][1];coordinates[i] = new Coordinate(longitude, latitude); // 注意经度在前,纬度在后}// 创建一个 GeometryFactory 对象GeometryFactory geometryFactory = new GeometryFactory();// 创建 LinearRing 对象LinearRing linearRing = geometryFactory.createLinearRing(coordinates);// 创建 Polygon 对象Polygon polygon = geometryFactory.createPolygon(linearRing);// 将 Polygon 对象的坐标赋值给 coords1Coordinate[] coords1 = polygon.getCoordinates();}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------//几何关系判断,是否相交intersection//其他方法类似//        相等(Equals): 几何形状拓扑上相等。//        不相交(Disjoint): 几何形状没有共有的点。//        相交(Intersects): 几何形状至少有一个共有点(区别于脱节)//        接触(Touches): 几何形状有至少一个公共的边界点,但是没有内部点。//        交叉(Crosses): 几何形状共享一些但不是所有的内部点。//        内含(Within): 几何形状A的线都在几何形状B内部。//        包含(Contains): 几何形状B的线都在几何形状A内部(区别于内含)//        重叠(Overlaps): 几何形状共享一部分但不是所有的公共点,而且相交处有他们自己相同的区域。

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.计算距离

        //计算距离distancePoint 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.计算长度和面积

        //计算距离distancePoint 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;}

这篇关于Java中使用JTS对空间几何计算(距离、点在面内、长度、面积、相交等)模拟的大概写法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/914429

相关文章

Spring IOC的三种实现方式详解

《SpringIOC的三种实现方式详解》:本文主要介绍SpringIOC的三种实现方式,在Spring框架中,IOC通过依赖注入来实现,而依赖注入主要有三种实现方式,构造器注入、Setter注入... 目录1. 构造器注入(Cons编程tructor Injection)2. Setter注入(Setter

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC

Spring Boot统一异常拦截实践指南(最新推荐)

《SpringBoot统一异常拦截实践指南(最新推荐)》本文介绍了SpringBoot中统一异常处理的重要性及实现方案,包括使用`@ControllerAdvice`和`@ExceptionHand... 目录Spring Boot统一异常拦截实践指南一、为什么需要统一异常处理二、核心实现方案1. 基础组件

java中的HashSet与 == 和 equals的区别示例解析

《java中的HashSet与==和equals的区别示例解析》HashSet是Java中基于哈希表实现的集合类,特点包括:元素唯一、无序和可包含null,本文给大家介绍java中的HashSe... 目录什么是HashSetHashSet 的主要特点是HashSet 的常用方法hasSet存储为啥是无序的

使用DeepSeek API 结合VSCode提升开发效率

《使用DeepSeekAPI结合VSCode提升开发效率》:本文主要介绍DeepSeekAPI与VisualStudioCode(VSCode)结合使用,以提升软件开发效率,具有一定的参考价值... 目录引言准备工作安装必要的 VSCode 扩展配置 DeepSeek API1. 创建 API 请求文件2.

使用TomCat,service输出台出现乱码的解决

《使用TomCat,service输出台出现乱码的解决》本文介绍了解决Tomcat服务输出台中文乱码问题的两种方法,第一种方法是修改`logging.properties`文件中的`prefix`和`... 目录使用TomCat,service输出台出现乱码问题1解决方案问题2解决方案总结使用TomCat,

IDEA运行spring项目时,控制台未出现的解决方案

《IDEA运行spring项目时,控制台未出现的解决方案》文章总结了在使用IDEA运行代码时,控制台未出现的问题和解决方案,问题可能是由于点击图标或重启IDEA后控制台仍未显示,解决方案提供了解决方法... 目录问题分析解决方案总结问题js使用IDEA,点击运行按钮,运行结束,但控制台未出现http://

解决Spring运行时报错:Consider defining a bean of type ‘xxx.xxx.xxx.Xxx‘ in your configuration

《解决Spring运行时报错:Considerdefiningabeanoftype‘xxx.xxx.xxx.Xxx‘inyourconfiguration》该文章主要讲述了在使用S... 目录问题分析解决方案总结问题Description:Parameter 0 of constructor in x

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时