import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.linearref.LengthIndexedLine;
import java.util.*;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
Coordinate[] cs1 = {new Coordinate(1, 0), new Coordinate(1, 2)};
Coordinate[] cs2 = {new Coordinate(0, 1), new Coordinate(1, 2)};
boolean result = checkSameDir(geometryFactory.createLineString(cs1), geometryFactory.createLineString(cs2));
System.out.println(result);
}
/**
* 两条线段角度差在0.35之内算同向
*/
public static boolean checkSameDir(LineString ln1, LineString ln2) {
double angleDif = 0.35;
int count1 = 0;
int count2 = 0;
List<Coordinate> coordinates = getLineStringPoints(ln1);
for (int i = 0; i < coordinates.size() - 1; i++) {
LineSegment lineSegment1 = new LineSegment(coordinates.get(i), coordinates.get(i + 1));
LineSegment lineSegment2 = getPointLatelyLineString(coordinates.get(i), ln2);
double angle2 = lineSegment2.angle();
double angle1 = lineSegment1.angle();
if (Math.abs(angle1 - angle2) < angleDif) {
count2++;
} else {
if (angle1 * angle2 < 0) {
count1++;
} else if (angle1 * angle2 > 0) {
count2++;
}
}
}
return count2 > count1;
}
/**
* 获取距离lineString最近的线段
*/
public static LineSegment getPointLatelyLineString(Coordinate coordinate, LineString lineString) {
CoordinateSequence coordinateSequence = lineString.getCoordinateSequence();
List<LineSegment> lineSegments = new ArrayList<>();
Coordinate prevCoordinate = coordinateSequence.getCoordinate(0);
for (int i = 1; i < coordinateSequence.size(); i++) {
Coordinate coordinate1 = coordinateSequence.getCoordinate(i);
LineSegment segment = new LineSegment(prevCoordinate, coordinate1);
if (segment.getLength() > 0) {
lineSegments.add(segment);
}
prevCoordinate = coordinate;
}
return lineSegments.stream()
.min(Comparator.comparing(lineSegment -> lineSegment.distance(coordinate))).orElse(new LineSegment());
}
/***
* 将lineString 分为20对点,按y抽拆,并且返回升序后的点对
* @param lineString
* @return
*/
public static List<Coordinate> getLineStringPoints(LineString lineString) {
int count = 20;
LengthIndexedLine lengthIndex = new LengthIndexedLine(lineString);
List<Coordinate> list = new ArrayList<>(count);
Coordinate[] coordinates = lineString.getCoordinates();
Map<Double, Coordinate> map = new HashMap<>(count);
for (int i = 1; i < count; i++) {
double offset = lineString.getLength() * ((double) i / count);
map.put(offset, lengthIndex.extractPoint(offset));
}
for (Coordinate coordinate : coordinates) {
map.put(lengthIndex.indexOf(coordinate), coordinate);
}
List<Map.Entry<Double, Coordinate>> orderList =
map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
orderList.forEach(e -> list.add(e.getValue()));
return list;
}
}
判断两个lineString是否同向
于 2021-12-27 10:40:45 首次发布