Here is a modified shapely cut function for splitting a line into segments.
from shapely.geometry import LineString, Point
def cut(line, distance, lines):
# Cuts a line in several segments at a distance from its starting point
if distance <= 0.0 or distance >= line.length:
return lines + [LineString(line)]
coords = list(line.coords)
for i, p in enumerate(coords):
pd = line.project(Point(p))
if pd == distance:
lines.append(LineString(coords[: i + 1]))
line = LineString(coords[i:])
return cut(line, distance, lines)
if pd > distance:
cp = line.interpolate(distance)
lines.append(LineString(coords[:i] + [(cp.x, cp.y)]))
line = LineString([(cp.x, cp.y)] + coords[i:])
return cut(line, distance, lines)
Some test 1
line = LineString([(6348053.180476057, 6652085.281694949), (6348206.3069751775, 6651979.8705129465)])
print(round(line.length, 4))
#185.9012
lines = cut(line, 30, list())
print([round(line.length, 4) for line in lines])
#[30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 5.9012]
Some test 2
line = LineString([(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0)])
print(round(line.length, 4))
#5.0
lines = cut(line, 2, list())
print([round(line.length, 4) for line in lines])
#[2.0, 2.0, 1.0]