mirror of
https://github.com/qgis/QGIS.git
synced 2025-03-17 00:02:54 -04:00
Algorithms and other processing code should use this method (instead of dataobjects.getLayerFromString) to retrieve layers from a string, as it considers the processing context and allows resolving strings to temporarily stored layers. This permits processing models to function correctly when intermediate results are stored as memory layers. Subsequent model algorithms can then access these temporary layers as inputs. All temporary layers will be removed when the context object is destroyed after the model algorithm is run.
32 lines
1.0 KiB
Python
32 lines
1.0 KiB
Python
##Centroids=name
|
|
##Geometry=group
|
|
##INPUT_LAYER=vector
|
|
##OUTPUT_LAYER=output vector
|
|
|
|
from qgis.core import QgsWkbTypes, QgsGeometry, QgsProcessingUtils
|
|
|
|
from processing.tools.vector import createVectorWriter
|
|
from processing.tools import dataobjects
|
|
|
|
layer = dataobjects.QgsProcessingUtils.mapLayerFromString(INPUT_LAYER, context)
|
|
fields = layer.fields()
|
|
|
|
writer, writer_dest, writer_layer = createVectorWriter(OUTPUT_LAYER, 'utf-8', fields, QgsWkbTypes.Point, layer.crs(),
|
|
context)
|
|
|
|
features = QgsProcessingUtils.getFeatures(layer, context)
|
|
count = QgsProcessingUtils.featureCount(layer, context)
|
|
if count == 0:
|
|
raise GeoAlgorithmExecutionException('Input layer contains no features.')
|
|
|
|
total = 100.0 / count
|
|
|
|
for count, f in enumerate(features):
|
|
outputFeature = f
|
|
if f.hasGeometry():
|
|
outputGeometry = f.geometry().centroid()
|
|
outputFeature.setGeometry(outputGeometry)
|
|
|
|
writer.addFeature(outputFeature)
|
|
feedback.setProgress(int(count * total))
|