Skip to content

Instantly share code, notes, and snippets.

@ghtmtt
Created October 5, 2018 19:20
Show Gist options
  • Save ghtmtt/3e682da4ce4fc0ddc0b67605a771e8e3 to your computer and use it in GitHub Desktop.
Save ghtmtt/3e682da4ce4fc0ddc0b67605a771e8e3 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from PyQt5.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
QgsFeatureSink,
QgsProcessingException,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterVectorLayer,
QgsProcessingParameterField,
QgsCoordinateReferenceSystem,
QgsProcessingParameterVectorDestination)
import processing
class Campo(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
INPUT = 'INPUT'
FIELD = 'FIELD'
BUFFER = 'BUFFER'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def createInstance(self):
return Campo()
def name(self):
return 'campo'
def displayName(self):
return self.tr('Campo')
def group(self):
return self.tr('Example scripts')
def groupId(self):
return 'examplescripts'
def initAlgorithm(self, config=None):
# We add the input vector features source. It can have any kind of
# geometry.
self.addParameter(
QgsProcessingParameterFeatureSource(
self.INPUT,
self.tr('Input layer'),
[QgsProcessing.TypeVectorAnyGeometry]
)
)
self.addParameter(
QgsProcessingParameterField(
self.FIELD,
self.tr("Campo"),
'STRANIERI',
self.INPUT
)
)
self.addParameter(
QgsProcessingParameterVectorDestination(
self.BUFFER,
self.tr('Buffer nativo')
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
def dummy(alg, context, feedback):
pass
# Retrieve the feature source and sink. The 'dest_id' variable is used
# to uniquely identify the feature sink, and must be included in the
# dictionary returned by the processAlgorithm function.
source = self.parameterAsVectorLayer(
parameters,
self.INPUT,
context
)
# If source was not found, throw an exception to indicate that the algorithm
# encountered a fatal error. The exception text can be any string, but in this
# case we use the pre-built invalidSourceError method to return a standard
# helper text for when a source cannot be evaluated
if source is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
campo = self.parameterAsFields(
parameters,
self.FIELD,
context
)[0]
buffer_output = self.parameterAsOutputLayer(
parameters,
self.BUFFER,
context
)
# If sink was not created, throw an exception to indicate that the algorithm
# encountered a fatal error. The exception text can be any string, but in this
# case we use the pre-built invalidSinkError method to return a standard
# helper text for when a sink cannot be evaluated
# Compute the number of steps to display within the progress bar and
# get features from source
total = 100.0 / source.featureCount() if source.featureCount() else 0
features = source.getFeatures()
# To run another Processing algorithm as part of this algorithm, you can use
# processing.run(...). Make sure you pass the current context and feedback
# to processing.run to ensure that all temporary layer outputs are available
# to the executed algorithm, and that the executed algorithm can send feedback
# reports to the user (and correctly handle cancelation and progress reports!)
for i in features:
buffered_layer = processing.run("native:buffer",
{
'INPUT': source,
'DISTANCE': i[campo],
'SEGMENTS': 5,
'END_CAP_STYLE': 0,
'JOIN_STYLE': 0,
'MITER_LIMIT': 2,
'DISSOLVE': False,
'OUTPUT': buffer_output
}, context=context, feedback=feedback, onFinish=dummy)['OUTPUT']
feedback.pushDebugInfo(str(i["STRANIERI"]))
reprojected = processing.run("native:reprojectlayer",
{
'INPUT': buffered_layer,
'TARGET_CRS': QgsCoordinateReferenceSystem('EPSG:4326'),
'OUTPUT':'memory:'
}, context=context, feedback=feedback)['OUTPUT']
# Return the results of the algorithm. In this case our only result is
# the feature sink which contains the processed features, but some
# algorithms may return multiple feature sinks, calculated numeric
# statistics, etc. These should all be included in the returned
# dictionary, with keys matching the feature corresponding parameter
# or output names.
return {self.BUFFER: reprojected}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment