5

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?

5

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

  • Thanks for this. Just to note that the last line doesn't work in QGIS 3, the following works instead: QgsProject.instance().addMapLayer(temp) Credit to Abhijit Gujar. – TeddyTedTed Jan 3 at 12:03
  • @TeddyTedTed You are right, thanks for pointing this! – YoLecomte Jan 3 at 22:03
5

You can use the GDAL/OGR tool: Create points along lines.

Make sure you specify 0.5 as the distance. This calculates the fraction of the total length (not the distance) as the tool incorporates the ST_Line_Interpolate_Point function.


Here is the default settings shown for me using QGIS 2.18.2 for Win7 64-bit:

Default settings

The attributes are also carried over to the output point layer.

1

I would suggest you use MMQGIS plugin that will allow you to find the mid point of the layer.

This provide a great resource to learn more about the plugin and the features. You would need to add the plugin via the repository in QGIS Describes use of MMQGIS, a set of Python vector map layer plugins for Quantum GIS

0

I use a two steps solution:

-First I make count densification with a count equals to one, this adds a mid point to every segment. -Then I extract specific nodes, indicating node number 1.

I use this solution because I keep not only the mid point, also the angle of the segment comes as an attribute. I have a model with the two steps inside, I only have to insert the lines layer

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.