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

相关文章

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

Spring @RequestMapping 注解及使用技巧详解

《Spring@RequestMapping注解及使用技巧详解》@RequestMapping是SpringMVC中定义请求映射规则的核心注解,用于将HTTP请求映射到Controller处理方法... 目录一、核心作用二、关键参数说明三、快捷组合注解四、动态路径参数(@PathVariable)五、匹配请

Java -jar命令如何运行外部依赖JAR包

《Java-jar命令如何运行外部依赖JAR包》在Java应用部署中,java-jar命令是启动可执行JAR包的标准方式,但当应用需要依赖外部JAR文件时,直接使用java-jar会面临类加载困... 目录引言:外部依赖JAR的必要性一、问题本质:类加载机制的限制1. Java -jar的默认行为2. 类加

Java进程CPU使用率过高排查步骤详细讲解

《Java进程CPU使用率过高排查步骤详细讲解》:本文主要介绍Java进程CPU使用率过高排查的相关资料,针对Java进程CPU使用率高的问题,我们可以遵循以下步骤进行排查和优化,文中通过代码介绍... 目录前言一、初步定位问题1.1 确认进程状态1.2 确定Java进程ID1.3 快速生成线程堆栈二、分析

Swagger在java中的运用及常见问题解决

《Swagger在java中的运用及常见问题解决》Swagger插件是一款深受Java开发者喜爱的工具,它在前后端分离的开发模式下发挥着重要作用,:本文主要介绍Swagger在java中的运用及常... 目录前言1. Swagger 的主要功能1.1 交互式 API 文档1.2 客户端 SDK 生成1.3

Java中的登录技术保姆级详细教程

《Java中的登录技术保姆级详细教程》:本文主要介绍Java中登录技术保姆级详细教程的相关资料,在Java中我们可以使用各种技术和框架来实现这些功能,文中通过代码介绍的非常详细,需要的朋友可以参考... 目录1.登录思路2.登录标记1.会话技术2.会话跟踪1.Cookie技术2.Session技术3.令牌技

Java 枚举的基本使用方法及实际使用场景

《Java枚举的基本使用方法及实际使用场景》枚举是Java中一种特殊的类,用于定义一组固定的常量,枚举类型提供了更好的类型安全性和可读性,适用于需要定义一组有限且固定的值的场景,本文给大家介绍Jav... 目录一、什么是枚举?二、枚举的基本使用方法定义枚举三、实际使用场景代替常量状态机四、更多用法1.实现接

java String.join()方法实例详解

《javaString.join()方法实例详解》String.join()是Java提供的一个实用方法,用于将多个字符串按照指定的分隔符连接成一个字符串,这一方法是Java8中引入的,极大地简化了... 目录bVARxMJava String.join() 方法详解1. 方法定义2. 基本用法2.1 拼接

java连接opcua的常见问题及解决方法

《java连接opcua的常见问题及解决方法》本文将使用EclipseMilo作为示例库,演示如何在Java中使用匿名、用户名密码以及证书加密三种方式连接到OPCUA服务器,若需要使用其他SDK,原理... 目录一、前言二、准备工作三、匿名方式连接3.1 匿名方式简介3.2 示例代码四、用户名密码方式连接4

springboot项目中使用JOSN解析库的方法

《springboot项目中使用JOSN解析库的方法》JSON,全程是JavaScriptObjectNotation,是一种轻量级的数据交换格式,本文给大家介绍springboot项目中使用JOSN... 目录一、jsON解析简介二、Spring Boot项目中使用JSON解析1、pom.XML文件引入依