I am relatively new to writing scripts in QGIS. I was wondering if pyqgis has any inbuilt functions that could take a distance parameter and remove that distance from the end of a target polyline.

I wasn't able to find what I was after in the pyqgis cookbook. I have used Shapely before and could manufacture a function, but I was hoping someone might know of pre-existing one.


To remove a specified distance from the end of a polyline, you can use these methods of QgsVectorLayer: 'insertVertex' and 'deleteVertex'. The first one is used to put a QgsPoint on the last polyline segment. This point was determined by using the slope and the intercept at origin of last polyline segment after subtracting the distance to remove. The second method is used to remove the last point from original polyline segment. Complete used code was:

from math import sqrt

layer = iface.activeLayer()

feats = [ feat for feat in layer.getFeatures() ]

line = [ feat.geometry().asPolyline() for feat in feats ]

n = len(line[0]) #first feature

#distance between last two points in last segment
dist = sqrt(line[0][n-2].sqrDist(line[0][n-1]))

new_dist = dist - 5000  #removing 5000 meters

#x,y coordinates of n-2 point
x1 = line[0][n-2][0] 
y1 = line[0][n-2][1]

#x,y coordinates of n-1 point
x2 = line[0][n-1][0] 
y2 = line[0][n-1][1]

#slope for last segment
m = (y2 - y1) / (x2 - x1)

#intercept at origin for last segment
int = y1 - m * x1

if new_dist > 0:
    #to find x, y coordinates for new point and distance
    a = 1
    b = -2*x1
    c = x1**2 - new_dist**2/(1+m**2)

    disc = b**2 -4*a*c

    new_x = (-b + sqrt(disc))/2*a
    new_y = m * new_x + int


    layer.insertVertex(new_x, new_y, 0, n-1)
    layer.deleteVertex(0, n)


    print "it's not possible to remove segment"

After cloning my polyline shapefile, to avoid modify the original layer, above code was run at the Python Console of QGIS and works as expected (see next image).

enter image description here

Code can be run until it is printed: "it's not possible to remove segment".


I share you some "cheats" by using qgis plugin.

  1. Reverse polyline direction.
  2. Plugin: Locate points along lines. Creating points along lines with given interval (for example: distance parameter 5 meters). polyline to points
  3. In the new point shapefile, delete those points which have distance less than 5 meters.
  4. Then, generate polyline from points (result of step 3).
  5. Last, reverse new polyline direction again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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