[GIS] Splitting line shapefile into segments of equal length using Python

linepythonshapefilesplitting

I want to split a line shapefile into segments of equal length, let say into lengths of x meters each. There is tool v.split.length as mentioned in this answer: How to split line into specific number of parts? Is there a way to do that in python without using QGIS?

Maybe using shapely and Fiona? as there is an interpolate method in shapely which could be used to add points at a specified distance on a line. But I couldn't find a way to divide a line into segments of a specified length.

Best Answer

Shapely can do what you ask. Here's an example of splitting a line string into 4 equal length parts.

from shapely.geometry import LineString, MultiPoint
from shapely.ops import split

line = LineString([(0, 0), (10, 10)])
splitter = MultiPoint([line.interpolate((i/4), normalized=True) for i in range(1, 4)])
split(line, splitter).wkt
# 'GEOMETRYCOLLECTION (LINESTRING (0 0, 2.5 2.5), LINESTRING (2.5 2.5, 5 5), LINESTRING (5 5, 7.5 7.5), LINESTRING (7.5 7.5, 10 10))'

It uses Shapely's interpolate() to find the points at which to split. Shapely's split() function is new in version 1.6.0. This method is general and doesn't depend on the number of points that define your line or whether it bends.

In practice, split() is sensitive to the points being precisely on the geometry you want to split. Floating point issues might confound you in some cases.