Thursday 20 June 2019

polyline creation - How can I switch line direction in QGIS?


Something that is hopefully pretty easy.


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 a couple of years ago, however I can't seem to find anything for QGIS.


Does anyone know of a tool to do this?



If one doesn't exist then I'm happy to have a go at making it, just didn't want to if one has already been made.



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...