Skip to main content
2 of 2
deleted unnecessary part of answer
Lars
  • 2.2k
  • 2
  • 19
  • 33

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.

Lars
  • 2.2k
  • 2
  • 19
  • 33