QGIS Convert Lines to Polygons – Troubleshooting Geometry Loss with “Convert Lines to Polygons” Tool in QGIS Python Console

pyqgisqgisqgis-processingqgis-python-consoleshapefile

I have found a bug with the "convert lines to polygon" tool of QGIS and would like to know if the bug is known and if there is a workaround?

I want to convert my MultiLineString Z to MultiPolygon Z with Qgis inside a plugin. The results from the processor tool are different from the Python console than from the tool interface.

Polygons are missing in the layer created via the Python console, while all polygons are in the output via the interface. Code and images follow below:

You can access the example data from my Google Drive in shapefile format: https://drive.google.com/drive/folders/1I_uhDnlvqjhrHZfUWmIpZoi-C5nDTG47?usp=sharing

The lines are extracted from citygml file from this source: https://www.opengeodata.nrw.de/produkte/geobasis/3dg/lod2_gml/lod2_gml/LoD2_32_352_5662_1_NW.gml

Python Console executed inside QGis.3.18 Python3.7:

import processing
test = "c:/Users/abc/Desktop/lod2_dev_test/LoD2_32_352_5662_1_NW.shp"
out = "c:/Users/abc/Desktop/lod2_dev_test/Polygone.shp"
processing.run("qgis:linestopolygons", {'INPUT':test,'OUTPUT':out}) 

The output looks like this:
Python Console missing polygon

if I run the same algorithm with the interface, the result is correct:

Tool Interface

Here the recorded command from the protocol:

processing.run("qgis:linestopolygons", {'INPUT':'c:/Users/abc/Desktop/lod2_dev_test/LoD2_32_352_5662_1_NW.shp','OUTPUT':'TEMPORARY_OUTPUT'})

The Polygon looks like this:

Result created from interface convert lines to polygon

Since I want to include the command in a plugin, I need the lines as polygons with z values. Does anyone know a solution for the bug or why the polygon is not written?

The lines definitely meet, that I checked in the WKT format of the shape.

Best Answer

It seems to be an issue with using shapefile as output. When using GeoPackage, it works seamlessly.

import processing
test = "c:/Users/abc/Desktop/LoD2_32_352_5662_1_NW.shp"
out = "ogr:dbname='C:/Users/abc/Desktop/out.gpkg' table='Polygone' (geom)"

# if you use the next line, you loose a geometry
# out = 'C:/Users/abc/Desktop/Polygone.shp'


result = processing.run("qgis:linestopolygons",
                        {'INPUT':test,'OUTPUT':out})["OUTPUT"]

layer = QgsVectorLayer(result, "Layer", "ogr")
QgsProject.instance().addMapLayer(layer)

With GeoPackage:

enter image description here

With shapefile:

enter image description here

Related Question