Monday, 17 August 2015

pyqgis - Geoprocessing LineIntersections QGIS Python


I am trying to make a QGIS plugin, and one of my goals is to use the geoprocessing tool "intersection" of QGIS into my Python code for the plugin. When I run it directly into QGIS, it works perfectly (especially transferring all attributes of both layers intersected).


When I run it in Python code, the result is the same but the attribute table does not contain all attributes (only one attribute...).


Here is an extract of my code for this purpose:


processing.runandload("qgis:lineintersections", final_layer1, final_layer2, "", "", output_intersect_path)

I also tested:



processing.runalg("qgis:lineintersections", final_layer1, final_layer2, "", "", output_intersect_path)
intersect_temp = QgsVectorLayer(output_intersect_path, output_intersect, "ogr")
QgsMapLayerRegistry.instance().addMapLayer(intersect_temp)

The problem lies in the parameters: final_layer1 and final_layer2 or the layers intersected. Then, the source help says "Field A" and "Field B", but I do not know what to put for those parameters in order to get all attributes transfered...


Does someone know how to do that ?




Here is my code:


    layer1_field = "last_fieldName"
layer2_field = "last_fieldName"


ouput_0 = processing.runalg("qgis:lineintersections", final_layer1, final_layer2, None, None, None)
output_1 = processing.runalg("qgis:joinattributestable", ouput_0['OUTPUT'], final_layer1, layer1_field, layer1_field, None)
result = processing.runandload("qgis:joinattributestable", output_1['OUTPUT_LAYER'], final_layer2, layer2_field, layer2_field, None)

Don`t know why it is not good at all....




Here are the source shapefiles to test.



Answer



The problem



Indeed, the QGIS Lines Intersection algorithm doesn't preserve all fields. It is only capable of keeping one field from each line layer. Moreover, if the fields that you choose from layer1 and layer2 have the same name, the algorithm only keeps the first one (from layer1).


Short term solution


You can get an adjusted Processing script for intersecting lines from my resource repository (https://github.com/gacarrillor/QGIS-Resources.git). Just install my scripts from the QGIS Resource Sharing plugin and you'll get the Lines Intersection Keep All Fields tool.


enter image description here


enter image description here


Mid-term solution


I've created a Pull Request (check it here) to fix this issue in Processing. It would enable you to get a field from each layer, all fields from both layers, or all fields from one layer and one field from the other.


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...