mtl_gis_oo/scrub_layer_class.py

52 lines
1.6 KiB
Python
Raw Normal View History

2024-03-15 16:43:27 -04:00
from qgis.core import QgsApplication, QgsField, QgsProject, \
QgsProcessingFeedback, QgsVectorLayer, QgsVectorDataProvider, \
QgsExpressionContext, QgsExpressionContextUtils
2024-03-15 12:08:52 -04:00
from qgis.analysis import QgsNativeAlgorithms
2024-03-15 16:43:27 -04:00
import processing
2024-03-15 11:26:23 -04:00
class ScrubLayer:
2024-03-15 12:08:52 -04:00
def __init__(self, qgis_path, layer_path, layer_name):
# Set the path to QGIS installation
QgsApplication.setPrefixPath(qgis_path, True)
# Initialize QGIS application
qgs = QgsApplication([], False)
qgs.initQgis()
2024-03-15 11:26:23 -04:00
self.layer_path = layer_path
self.layer_name = layer_name
2024-03-15 12:08:52 -04:00
self.layer = self.load_layer()
2024-03-15 11:26:23 -04:00
2024-03-15 12:08:52 -04:00
def load_layer(self):
the_layer = QgsVectorLayer(self.layer_path, self.layer_name, 'ogr')
2024-03-15 11:26:23 -04:00
if not the_layer.isValid():
2024-03-15 12:08:52 -04:00
raise ValueError(f'Failed to load layer {self.layer_name} from {self.layer_path}')
2024-03-15 11:26:23 -04:00
else:
2024-03-15 12:08:52 -04:00
QgsProject.instance().addMapLayer(the_layer)
return the_layer
2024-03-15 16:43:27 -04:00
def create_spatial_index(self):
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
create_spatial_index_params = {
'INPUT': self.layer_path,
'OUTPUT': 'Output'
}
processing.run("native:createspatialindex", create_spatial_index_params)
2024-03-15 12:08:52 -04:00
@staticmethod
def cleanup():
QgsApplication.exitQgis()
2024-03-15 11:26:23 -04:00
if __name__ == '__main__':
2024-03-15 12:08:52 -04:00
app_path = 'C:/Program Files/QGIS 3.34.1/apps/qgis'
new_path = 'C:/Users/a_adli/PycharmProjects/hydroquebec_archetype_gispy/' \
2024-03-15 16:43:27 -04:00
'data/test_data/test_input/nrcan_north/nrcan_north.shp'
data_layer_name = 'nrcan_north'
handle_layer = ScrubLayer(app_path, new_path, data_layer_name)
# print(handle_layer.layer.featureCount())
handle_layer.create_spatial_index()
2024-03-15 12:08:52 -04:00