GeoTools: Calculate length along line from start vertex up to some point on the line?
1) Try this:
public static double calculateLengthAlongLineString(LineString theLine, Coordinate coordinateOnTheLine){
GeometryFactory factory = new GeometryFactory();
double length = 0;
// create point to check for intersection with line
Point pointOnTheLine = factory.createPoint(coordinateOnTheLine);
Coordinate[] theLineCoordinates = theLine.getCoordinates();
// iterate over linestring and create sub-lines for each coordinate pair
for(int i = 1; i < theLineCoordinates.length; i++){
LineString currentLine = factory.createLineString(new Coordinate[]{theLineCoordinates[i-1], theLineCoordinates[i]});
// check if coordinateOnTheLine is on currentLine
if(currentLine.intersects(pointOnTheLine)){
// create new currentLine with coordinateOnTheLine as endpoint and calculate length
currentLine = factory.createLineString(new Coordinate[]{theLineCoordinates[i-1], coordinateOnTheLine});
length += currentLine.getLength();
// return result length
return length;
}
length += currentLine.getLength();
}
// coordinate was not on the line -> return length of complete linestring...
return length;
}
This approach is similar to what you already suggested. Each LineString segment is checked for intersection with the point (coordinate) and then the length is summed up.
2)
Not to my knowledge.
I think it's a better way to get length by JTS.
import org.locationtech.jts.linearref.LengthIndexOfPoint;
LineString theLine = ...;
Coordinate pt = ...;
double length = LengthIndexOfPoint.indexOf(theLine, pt);
For details see source code of JTS