53

I would like to be able to swap the direction of a polyline/line in QGIS. I made a custom tool to do this in MapInfo, however I can't seem to find anything for QGIS.

Does anyone know of a tool to do this?

5

8 Answers 8

66

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:

  1. Select the layer you want to edit;
  2. Toggle Editing on;
  3. Select the features in this layer you want to reverse.

Run the above python code by:

  1. Going to Plugins > Python Console;
  2. Copying and pasting the code into the window;
  3. 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.

13
  • 1
    so you created your own solution - well done - can it be added to ftools?
    – Mapperz
    Commented May 4, 2011 at 21:36
  • I'm sure it can, I'll just have to look at the way fTools is coded and write a patch.
    – Nathan W
    Commented May 4, 2011 at 22:02
  • Fantastic! Solutions like this are the reason I like using QGIS. Nice job Nathan - BTW I like your little catalogue type plugin aswell!
    – Ando
    Commented May 4, 2011 at 22:05
  • @Ando Thanks! I'm beta testing a few new ideas, just wish I had more time to work on it so I could get it out quicker.
    – Nathan W
    Commented May 4, 2011 at 22:17
  • 3
    That is really awesome that you worked up a solution so quickly and elegantly. The power of Open Source wins again! Commented May 4, 2011 at 22:20
16

If you have the GRASS plugin use the v.flip option - http://grass.osgeo.org/wiki/GRASS_AddOns#v.flip

enter image description here

3
  • hmmm was hoping for a more QGIS native way, don't have GRASS install at the moment. But it's a good tip for people that do.
    – Nathan W
    Commented May 4, 2011 at 5:55
  • would be good to have in python and add to ftools noted by underdark.
    – Mapperz
    Commented May 4, 2011 at 13:41
  • Now it is found in [ Vector geometry | Reverse line direction ] Commented Jul 12, 2022 at 13:04
8

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!

1
  • 1
    this code is for 2.x Commented Dec 12, 2013 at 7:33
6

This plugin reverses the line direction too:

https://hub.qgis.org/projects/swapvectordirection

You have to select a feature, and turn the layer into edit mode before clicking on the plugin icon.

6

Based on Nathan's post I've created a processing script to reverse the direction of features:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# define Interface
##QGIS tools (QGIS 2.x)=group
##Reverse vector direction=name
##Input_layer=vector
##Only_selected_features=boolean true

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import *

from qgis.core import *
from qgis.gui import *
from qgis.utils import *

# get input parameters from GUI
inlayer = processing.getObject(Input_layer)
selected = Only_selected_features

# check 'Only selected features' option
if selected is True and inlayer.selectedFeatureCount () == 0:
    raise RuntimeError('No features selected on Layer \'' + inlayer.name() + '\'.')

# check if input layer is editable
if not inlayer.isEditable():
    inlayer.startEditing()

# reverse vector direction
def reverse():
    geom = feature.geometry()
    nodes = geom.asPolyline()
    nodes.reverse()
    newgeom = QgsGeometry.fromPolyline(nodes)
    inlayer.changeGeometry(feature.id(),newgeom)

if selected is True:
    for feature in inlayer.selectedFeatures():
        reverse()
else:
    for feature in inlayer.getFeatures():
        reverse()

# refresh input layer
inlayer.dataProvider().forceReload()

enter image description here

3
4

This plugin will switch the direction of a polyline.

http://plugins.qgis.org/plugins/DigitizingTools/

2

Since QGIS 2.14 (see the Changelog) there is the "Reverse line direction" (placed in Vector geometry) tool from the Processing Toolbox (Ctrl+Alt+T).

Let's assume there are two features in 'lines_test', see the image below.

input

Press Run and get the output:

output

0

Using QGIS 3.10

Following @Nathan W 's answer above, here's a solution if your line is a LineStringZ (i.e. a line with an x, y and Z value) - as are most Google Earth KML files (even if that Z value = 0, which is often the case.)

You might get this error when the nodes.reverse() call is made in the code below:

TypeError: index 0 has type QgsPointXY but QgsPoint is expected

1   layer = qgis.utils.iface.mapCanvas().currentLayer()
2   for feature in layer.selectedFeatures():
3      geom = feature.geometry()
4      nodes = geom.asPolyline()
5      nodes.reverse() 
6      newgeom = QgsGeometry.fromPolyline(nodes)
7      layer.changeGeometry(feature.id(), newgeom)

The solution to that is to use QgsGeometry.fromPolylineXY() instead in line 6:

1   vLayer = qgis.utils.iface.mapCanvas().currentLayer()
2   for feat in vLayer.selectedFeatures():
3       geom = feat.geometry()
4       pointXY_nodes = geom.asPolyline() # >>> returns list of QgsPointXY objects: [<QgsPointXY: POINT(-117.60560599 ..
5       pointXY_nodes.reverse() 
6       newgeom = QgsGeometry.fromPolylineXY(pointXY_nodes)
7       vLayer.changeGeometry(feat.id(), newgeom)
8       print("Geom reversed!")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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