3

I'm using QGIS 2.18.9.

How do I split a line by percentage?

In the case of a line, split it by percentage length.

My use-case is more for roads where I would like to split a segment (by %). So, I can use the line feature to determine the length and then create a buffer as shown.

enter image description here

3
  • 1
    Splitting a polygon by a percentage should be a different question to splitting a line by a percentage. I think you should focus this one on the former, and if the other is not already asked and answered on this site, then ask that separately.
    – PolyGeo
    Jul 11, 2017 at 1:36
  • 1
    Out of curiosity, what happened to the other 10%? ;)
    – Joseph
    Jul 13, 2017 at 13:23
  • 1
    you got my red handed @Joseph. :) its a mistake
    – Garry
    Aug 30, 2017 at 3:25

1 Answer 1

3

You may run this simple code from the Python Console:

percentage = 0.6 # Set the percentage

layer = iface.activeLayer() # Load it as you want

# Create the output layer
crs = layer.crs().toWkt()
outLayer = QgsVectorLayer('Polygon?crs='+ crs, 'catchments_new' , 'memory')
prov = outLayer.dataProvider()
fields = layer.pendingFields() # Fields from the input layer
prov.addAttributes(fields) # Add input layer fields to the outLayer
outLayer.updateFields()

for feat in layer.getFeatures():
    attrs = feat.attributes()
    line_geom = feat.geometry()
    leng = line_geom.length()
    print leng
    dist = (percentage * leng)
    center_pt = dist * 0.5
    pt = line_geom.interpolate(center_pt)
    buffered_geom = pt.buffer(center_pt, 2000) # set the second parameter sufficiently enough for avoiding creating odd behaviors
    itx = line_geom.intersection(buffered_geom)
    diff = line_geom.difference(buffered_geom)

    outGeom_1 = QgsFeature()
    outGeom_1.setAttributes(attrs)
    outGeom_1.setGeometry(buffered_geom)
    prov.addFeatures([outGeom_1])

    outGeom_2 = QgsFeature()
    outGeom_2.setAttributes(attrs)
    outGeom_2.setGeometry(diff)
    prov.addFeatures([outGeom_2])

# Add the layer to the Layers panel
QgsMapLayerRegistry.instance().addMapLayer(outLayer)

It will create a new line memory layer that stores each original line feature as two splitted new features depending on the percentage you have set.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.