[GIS] Creating points along line according to attribute data using QGIS

points-to-lineqgis

I would like to create equidistant points along lines in QGIS, but each of my lines have an attribute of how many points should be on them in a column called "piece" and these values are different in almost every case.

enter image description here

My first thought was to divide lines to equal pieces according to the values in the attribute table and then put points to the centroids of the lines but I could not do it.

This question is very similar to what I would like to do, but it is not for QGIS:

How to create the same number of points along multiple polylines?

Most similar questions that can be found here at stackexchange in this topic are about a specific distance between points, a number that can be easily typed into a field (like in the case of Create points along lines or Convert lines to points algorithms) and not about specific data from an attribute table, which I've been unable to find how to use for such purposes.

It would be fantastic if there were no points right at the start and end point of the line but I would be just over the moon if there were as many points on a line as in its attribute table.

Best Answer

Here's a quick PyQGIS script which should do the trick

from qgis.core import QgsFeature, QgsVectorFileWriter, QgsGeometry

def create_points(feat,writer):
    geometry = feat.constGeometry()
    if not geometry:
        return
    length = geometry.length()
    # -----------------
    # change 'num_points' to match your field name for the number of points field
    # -----------------
    num_points = feat['num_points']
    delta = length / ( num_points + 1.0 )
    distance = 0.0
    for i in range(num_points):
        distance += delta
        output_feature = QgsFeature(feat)
        output_feature.setGeometry( geometry.interpolate(distance) )
        writer.addFeature(output_feature)

layer = iface.activeLayer()

# ---------------
# change 'd:/test_points.shp' to desired output file name
# ---------------

writer = QgsVectorFileWriter('d:/test_points.shp',None, layer.fields(), QGis.WKBPoint, layer.crs())

for f in layer.getFeatures():
    create_points(f,writer)

del writer

Just change the num_points field name and output file name to match your data, select the input layer, and run it in the python console.

Related Question