0

I am writing a QGIS plugin and for part of the process, I want to transform a Line layer (connected lines) into a Polygon layer. For this, I am using processing.run('qgis:linestopolygons') command. However, the results are not satisfactory. There are several polygons missing and I get some small polygons. Here is the Code I am using for polygon creation:

if result:
    # Do something useful here - delete the line containing pass and
    # substitute with your code.
    filename_csv = self.dlg.lineEdit.text()
    filename_shp = self.dlg.lineEdit_2.text()
    print(filename_shp)
    print(filename_csv)
    shapefile_path = os.path 
    with open(filename_csv, 'w') as output_file:
        selectedLayerIndex = self.dlg.comboBox.currentIndex()
        selectedLayer = layers[selectedLayerIndex].layer()
        print(selectedLayer)
        print(shapefile_path)
        fieldnames = [field.name() for field in selectedLayer.fields()]
        # write header
        line = ','.join(name for name in fieldnames) + '\n'
        output_file.write(line)

        print(selectedLayer)

        # this part of the code is used for polygonize the line layer
        processing.run('qgis:linestopolygons', {'INPUT': selectedLayer, 'OUTPUT': 'C:/Users/user/Desktop/GJ/four.shp'})
        
        # this is used to write shapefile from an input
        QgsVectorFileWriter.writeAsVectorFormat(
            selectedLayer, 
            filename_shp,
            'utf-8',
            selectedLayer.crs(),
            'ESRI Shapefile')
        # wirte feature attributes
        for f in selectedLayer.getFeatures():
            line = ','.join(str(f[name]) for name in fieldnames) + '\n'
            output_file.write(line)

        self.iface.messageBar().pushMessage(
            "Success", "Output file written at " + filename_csv,
            level=Qgis.Success, duration=3)

Here is the output map (the green color represents the line layer and the brown color represents the putout polygon layer):

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.