How can I switch line direction in QGIS?
Ok here is the Python that I used to do it:
layer = qgis.utils.iface.mapCanvas().currentLayer()
for feature in layer.selectedFeatures():
geom = feature.geometry()
nodes = geom.asPolyline()
nodes.reverse()
newgeom = QgsGeometry.fromPolyline(nodes)
layer.changeGeometry(feature.id(),newgeom)
Before running the above code:
- Select the layer you want to edit;
- Toggle Editing on;
- Select the features in this layer you want to reverse.
Run the above python code by:
- Going to Plugins > Python Console;
- Copying and pasting the code into the window;
- Hit Enter 2x to run.
It should output "True" for each feature whose direction was swapped. If it outputs "False" then it didn't swap that feature's direction. This will happen if the layer doesn't have Editing toggled on.
Pretty easy!
I have wrapped it up in a plugin called Swap Line Direction
and it's available in the QGIS plugin installer.
This plugin is no longer available (as of 11/16/2015) in the plugin installer but you can build your own pretty easily with the "Plugin Builder" plugin.
I'll have a look at how easy it is to intergrate with fTools.
If you have the GRASS plugin use the v.flip option - http://grass.osgeo.org/wiki/GRASS_AddOns#v.flip
Following Nathan's answer, you can create a python action in the layer where you want to swap lines:
layer = QgsMapLayerRegistry.instance().mapLayer("_your_layer_id_")
r = QgsFeatureRequest([% $id %])
f = QgsFeature()
if layer.getFeatures(r).nextFeature(f):
geom = f.geometry().asPolyline()
geom.reverse()
geom = QgsGeometry.fromPolyline(geom)
if layer.changeGeometry([% $id %], geom):
qgis.utils.iface.messageBar().pushMessage("Line swaped", QgsMessageBar.INFO, 2)
qgis.utils.iface.mapCanvas().refresh()
else:
qgis.utils.iface.messageBar().pushMessage("Cannot swap line. Turn editing on.", QgsMessageBar.WARNING, 3)
else:
qgis.utils.iface.messageBar().pushMessage("Cannot edit this feature.", QgsMessageBar.CRITICAL, 3)
You will be able to swap lines by one click on them. It is much user-friendly!