[GIS] Create mid point from line layer

distancelinepointpoints-to-lineqgis

In QGIS I am trying to create a new point layer based on the mid point of a line layer (and keep all the feature attributes in the table).

For example, one line feature becomes one point, located on the mid/center point of the line. Points to lines only seems to work on nodes, and Create points along lines only seems to work at fixed distances?

Best Answer

If python is Ok for you, you can easily do that with that code snippet. Copy/paste this code in the editor of the python console, select your line layer and run the script!

layer = iface.activeLayer()

temp = QgsVectorLayer("Point?crs=epsg:2154", "result", "memory")
temp.startEditing()

attrs = layer.dataProvider().fields().toList()
temp_prov = temp.dataProvider()
temp_prov.addAttributes(attrs)
temp.updateFields()

for elem in layer.getFeatures():
    feat = QgsFeature()
    geom = elem.geometry().interpolate(elem.geometry().length()/2)
    feat.setGeometry(geom)
    feat.setAttributes(elem.attributes())
    temp.addFeatures([feat])
    temp.updateExtents()

temp.commitChanges()
QgsMapLayerRegistry.instance().addMapLayer(temp)

This code also take care about keeping the attributes of the line Layer. Here is my result on a set of line :

enter image description here

Related Question