JTS介绍
Github项目地址:https://github.com/locationtech/jts
Maven库地址:https://mvnrepository.com/artifact/org.locationtech.jts
JTS Topology Suite是一个用于创建和操作二维矢量几何的Java库。
JTS有对应的.NET版本NetTopologySuite库,因此JTS和NTS的相关功能能够方便地转化和迁移(一方的功能在另一方基本都能找到对应的功能类)。
创建一个几何,并对其进行平移、旋转
以JDK1.8为测试环境,先通过Maven安装JTS库:
<dependency>
<groupId>org.locationtech.jts</groupId>
<artifactId>jts-core</artifactId>
<version>1.19.0</version>
</dependency>
平移工具类
该平移是在原坐标x、y基础上,分别增加一个参数dx和dy。
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateSequenceFilter;
public class GeoOffset implements CoordinateSequenceFilter {
@Override
public void filter(CoordinateSequence coordinateSequence, int i) {
coordinateSequence.setOrdinate(i, 0, coordinateSequence.getX(i) + dx);
coordinateSequence.setOrdinate(i, 1, coordinateSequence.getY(i) + dy);
}
private double dx;
private double dy;
public GeoOffset(double dx, double dy)
{
this.dx = dx;
this.dy = dy;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isGeometryChanged() {
return false;
}
}
平移测试用例
public void testGeoOffset() throws Exception {
WKTReader r = new WKTReader();
Geometry g = r.read("polygon((0 0,0 1,1 1,1.5 0,1 -1, 0 0))");
GeoOffset geooffset = new GeoOffset(2, -0.5);
g.apply(geooffset);
System.out.println(g.toText());//POLYGON ((2 -0.5, 2 0.5, 3 0.5, 3.5 -0.5, 3 -1.5, 2 -0.5))
}
平移前后图形示意图:
缩放
缩放工具类
该缩放时是在原坐标基础上乘以一个系数scale。
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateSequenceFilter;
public class GeoScale implements CoordinateSequenceFilter {
@Override
public void filter(CoordinateSequence coordinateSequence, int i) {
coordinateSequence.setOrdinate(i, 0, coordinateSequence.getX(i) * scale);
coordinateSequence.setOrdinate(i, 1, coordinateSequence.getY(i) * scale);
}
private double scale;
public GeoScale(double scale)
{
this.scale = scale;
}
@Override
public boolean isDone() {
return false;
}
@Override
public boolean isGeometryChanged() {
return false;
}
}
缩放测试用例
public void testGeoScale() throws Exception {
WKTReader r = new WKTReader();
Geometry g = r.read("polygon((0 0,0 1,1 1,1.5 0,1 -1, 0 0))");
GeoScale geoScale = new GeoScale(2);
g.apply(geoScale);
System.out.println(g.toText());//POLYGON ((0 0, 0 2, 2 2, 3 0, 2 -2, 0 0))
}
其他变换
可以根据需要,自定义需要的坐标变换,方法是:
先创建一个类并实现CoordinateSequenceFilter
接口,然后自定义filter
函数。
例如平移时的filter
函数:
@Override
public void filter(CoordinateSequence coordinateSequence, int i) {
coordinateSequence.setOrdinate(i, 0, coordinateSequence.getX(i) + dx);
coordinateSequence.setOrdinate(i, 1, coordinateSequence.getY(i) + dy);
}
旋转时的filter
函数:
@Override
public void filter(CoordinateSequence coordinateSequence, int i) {
coordinateSequence.setOrdinate(i, 0, coordinateSequence.getX(i) * scale);
coordinateSequence.setOrdinate(i, 1, coordinateSequence.getY(i) * scale);
}