PyQGIS Segmentizing – MultiLineString by Distance

pyqgissegment

I want to segmentize a MultiLineString layer by a given maximum distance. Result shall be parts of the input linestring with this maximum length. I am using QGIS 3.16 and want a pure PyQGIS solution.

Note: It took a while to research and I could not find a question or answer for PyQGIS, so this is written as self-answer question, therefore no codeattempt. But of course, please add your solution!

Best Answer

You can iterate over the parts of the MultiLines and use QgsLineString.curveSubstring() to create the segments. To know the number of segments as well as start- and endpoints of the segments you only need some simple math:

import math
linelayer = iface.activeLayer()
distance = 1000

vl = QgsVectorLayer("LineString?crs={}".format(linelayer.crs().authid()), "temp", "memory")
vl.startEditing()

for line in linelayer.getFeatures():
    linegeom = line.geometry()
    for linepart in linegeom.parts():
        linepartgeom = QgsGeometry.fromPolyline(linepart)
        partlength = linepartgeom.length()
        nsegments = math.ceil(partlength / distance)
        startdist = 0
        enddist = distance
        for segment in range(0,nsegments):
            segmentlinestring = linepart.curveSubstring(startdist,enddist)
            segmentgeom = QgsGeometry.fromPolyline(segmentlinestring)
            startdist += distance
            enddist += distance
            # Do something with that segment #
            
            f = QgsFeature()
            f.setGeometry(segmentgeom)
            vl.dataProvider().addFeature(f)
vl.updateExtents()
vl.commitChanges()
QgsProject.instance().addMapLayer(vl)
Related Question