From 4b85e48debb646865905b365b2766466accd1f4d Mon Sep 17 00:00:00 2001 From: Alireza Adli Date: Mon, 21 Oct 2024 13:03:17 -0400 Subject: [PATCH] Convert features to shape layers --- scrub_layer_class.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/scrub_layer_class.py b/scrub_layer_class.py index ff5b37e..087fe73 100644 --- a/scrub_layer_class.py +++ b/scrub_layer_class.py @@ -8,7 +8,7 @@ Project Developer: Alireza Adli alireza.adli@concordia.ca from qgis.core import QgsApplication, QgsField, QgsProject, \ QgsProcessingFeedback, QgsVectorLayer, QgsVectorDataProvider, \ QgsExpressionContext, QgsExpressionContextUtils, edit, QgsFeatureRequest, \ - QgsExpression, QgsVectorFileWriter + QgsExpression, QgsVectorFileWriter, QgsCoordinateReferenceSystem from qgis.PyQt.QtCore import QVariant from qgis.analysis import QgsNativeAlgorithms from basic_functions import * @@ -69,8 +69,27 @@ class ScrubLayer: QgsProject.instance().addMapLayer(the_layer) return the_layer - def features_to_layers(self): - pass + def features_to_layers(self, layers_dir, crs): + create_folders(layers_dir, self.data_count) + target_crs = QgsCoordinateReferenceSystem(crs) + for feature in self.layer.getFeatures(): + new_layer = QgsVectorLayer(f'Polygon?crs={crs}', "feature_layer", "memory") + new_layer.setCrs(target_crs) + + new_provider = new_layer.dataProvider() + new_provider.addFeatures([feature]) + + feature_id = feature.id() + output_path = f'{layers_dir}layer_{feature_id}/layer_{feature_id}.shp' + + QgsVectorFileWriter.writeAsVectorFormat( + new_layer, + output_path, + 'utf-8', + new_layer.crs(), + 'ESRI Shapefile' + ) + print('Shapefiles created for each feature.') def fix_geometries(self, fixed_layer): QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())