QGIS API Documentation 3.41.0-Master (fda2aa46e9a)
Loading...
Searching...
No Matches
qgsalgorithmmultiintersection.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmmultiintersection.cpp
3 ------------------
4 begin : December 2021
5 copyright : (C) 2021 by Alexander Bruy
6 email : alexander dot bruy at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "qgsoverlayutils.h"
21#include "qgsvectorlayer.h"
22
24
25
26QString QgsMultiIntersectionAlgorithm::name() const
27{
28 return QStringLiteral( "multiintersection" );
29}
30
31QString QgsMultiIntersectionAlgorithm::displayName() const
32{
33 return QObject::tr( "Intersection (multiple)" );
34}
35
36QStringList QgsMultiIntersectionAlgorithm::tags() const
37{
38 return QObject::tr( "intersection,extract,overlap" ).split( ',' );
39}
40
41QString QgsMultiIntersectionAlgorithm::group() const
42{
43 return QObject::tr( "Vector overlay" );
44}
45
46QString QgsMultiIntersectionAlgorithm::groupId() const
47{
48 return QStringLiteral( "vectoroverlay" );
49}
50
51QString QgsMultiIntersectionAlgorithm::shortHelpString() const
52{
53 return QObject::tr( "This algorithm extracts the overlapping portions of features in the Input and all Overlay layers. "
54 "Features in the output layer are assigned the attributes of the overlapping features "
55 "from both the Input and Overlay layers." );
56}
57
58Qgis::ProcessingAlgorithmDocumentationFlags QgsMultiIntersectionAlgorithm::documentationFlags() const
59{
61}
62
63QgsProcessingAlgorithm *QgsMultiIntersectionAlgorithm::createInstance() const
64{
65 return new QgsMultiIntersectionAlgorithm();
66}
67
68void QgsMultiIntersectionAlgorithm::initAlgorithm( const QVariantMap & )
69{
70 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ) ) );
71 addParameter( new QgsProcessingParameterMultipleLayers( QStringLiteral( "OVERLAYS" ), QObject::tr( "Overlay layers" ), Qgis::ProcessingSourceType::VectorAnyGeometry ) );
72
73 std::unique_ptr< QgsProcessingParameterString > prefix = std::make_unique< QgsProcessingParameterString >( QStringLiteral( "OVERLAY_FIELDS_PREFIX" ), QObject::tr( "Overlay fields prefix" ), QString(), false, true );
74 prefix->setFlags( prefix->flags() | Qgis::ProcessingParameterFlag::Advanced );
75 addParameter( prefix.release() );
76
77 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Intersection" ) ) );
78}
79
80QVariantMap QgsMultiIntersectionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
81{
82 std::unique_ptr< QgsFeatureSource > sourceA( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
83 if ( !sourceA )
84 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
85
86 const QList< QgsMapLayer * > layers = parameterAsLayerList( parameters, QStringLiteral( "OVERLAYS" ), context );
87
88 // loop through overlay layers and check whether they are vectors
89 long totalLayerCount = 0;
90 for ( QgsMapLayer *layer : layers )
91 {
92 if ( feedback->isCanceled() )
93 break;
94
95 if ( !layer )
96 throw QgsProcessingException( QObject::tr( "Error retrieving map layer." ) );
97
98 if ( layer->type() != Qgis::LayerType::Vector )
99 throw QgsProcessingException( QObject::tr( "All layers must be vector layers!" ) );
100
101 totalLayerCount++;
102 }
103
104 const QString overlayFieldsPrefix = parameterAsString( parameters, QStringLiteral( "OVERLAY_FIELDS_PREFIX" ), context );
105
106 const Qgis::WkbType geometryType = QgsWkbTypes::multiType( sourceA->wkbType() );
107 const QgsCoordinateReferenceSystem crs = sourceA->sourceCrs();
108 std::unique_ptr< QgsFeatureSink > sink;
109 long count = 0;
110 QVariantMap outputs;
111
112 QList<int> fieldIndicesA, fieldIndicesB;
113 QgsFields outputFields;
114
115 if ( totalLayerCount == 1 )
116 {
117 QgsVectorLayer *overlayLayer = qobject_cast< QgsVectorLayer * >( layers.at( 0 ) );
118
119 fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), sourceA->fields() );
120 fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), overlayLayer->fields() );
121
123 QgsProcessingUtils::indicesToFields( fieldIndicesA, sourceA->fields() ),
124 QgsProcessingUtils::indicesToFields( fieldIndicesB, overlayLayer->fields() ),
125 overlayFieldsPrefix );
126
127 QString dest;
128 sink.reset( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outputFields, geometryType, crs, QgsFeatureSink::RegeneratePrimaryKey ) );
129 if ( !sink )
130 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
131
132 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
133
134 const long total = sourceA->featureCount();
135 QgsOverlayUtils::intersection( *sourceA, *overlayLayer, *sink, context, feedback, count, total, fieldIndicesA, fieldIndicesB );
136 }
137 else
138 {
139 QgsProcessingMultiStepFeedback multiStepFeedback( totalLayerCount, feedback );
140 QgsVectorLayer *intersectionLayer = nullptr;
141
142 long i = 0;
143 for ( QgsMapLayer *layer : layers )
144 {
145 if ( feedback->isCanceled() )
146 break;
147
148 multiStepFeedback.setCurrentStep( i );
149
150 if ( !layer )
151 continue;
152
153 QgsVectorLayer *overlayLayer = qobject_cast< QgsVectorLayer * >( layer );
154 if ( !overlayLayer )
155 continue;
156
157 count = 0;
158 if ( i == 0 )
159 {
160 fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), sourceA->fields() );
161 fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), overlayLayer->fields() );
162
164 QgsProcessingUtils::indicesToFields( fieldIndicesA, sourceA->fields() ),
165 QgsProcessingUtils::indicesToFields( fieldIndicesB, overlayLayer->fields() ),
166 overlayFieldsPrefix );
167
168 QString id = QStringLiteral( "memory:" );
169 sink.reset( QgsProcessingUtils::createFeatureSink( id, context, outputFields, geometryType, crs ) );
170 QgsOverlayUtils::intersection( *sourceA, *overlayLayer, *sink, context, &multiStepFeedback, count, sourceA->featureCount(), fieldIndicesA, fieldIndicesB );
171
172 intersectionLayer = qobject_cast< QgsVectorLayer * >( QgsProcessingUtils::mapLayerFromString( id, context ) );
173 }
174 else if ( i == totalLayerCount - 1 )
175 {
176 fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), intersectionLayer->fields() );
177 fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), overlayLayer->fields() );
178
180 QgsProcessingUtils::indicesToFields( fieldIndicesA, intersectionLayer->fields() ),
181 QgsProcessingUtils::indicesToFields( fieldIndicesB, overlayLayer->fields() ),
182 overlayFieldsPrefix );
183
184 QString dest;
185 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outputFields, geometryType, crs ) );
186 if ( !sink )
187 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
188
189 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
190
191 QgsOverlayUtils::intersection( *intersectionLayer, *overlayLayer, *sink, context, &multiStepFeedback, count, intersectionLayer->featureCount(), fieldIndicesA, fieldIndicesB );
192 }
193 else
194 {
195 fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), intersectionLayer->fields() );
196 fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), overlayLayer->fields() );
197
199 QgsProcessingUtils::indicesToFields( fieldIndicesA, intersectionLayer->fields() ),
200 QgsProcessingUtils::indicesToFields( fieldIndicesB, overlayLayer->fields() ),
201 overlayFieldsPrefix );
202
203 QString id = QStringLiteral( "memory:" );
204 sink.reset( QgsProcessingUtils::createFeatureSink( id, context, outputFields, geometryType, crs ) );
205 QgsOverlayUtils::intersection( *intersectionLayer, *overlayLayer, *sink, context, &multiStepFeedback, count, intersectionLayer->featureCount(), fieldIndicesA, fieldIndicesB );
206
207 intersectionLayer = qobject_cast< QgsVectorLayer * >( QgsProcessingUtils::mapLayerFromString( id, context ) );
208 }
209
210 i++;
211 }
212 }
213
214 return outputs;
215}
216
@ VectorAnyGeometry
Any vector layer with geometry.
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
@ Vector
Vector layer.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3359
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:256
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
This class represents a coordinate reference system (CRS).
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
Container of fields for a vector layer.
Definition qgsfields.h:46
Base class for all map layer types.
Definition qgsmaplayer.h:76
Abstract base class for processing algorithms.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
Processing feedback object for multi-step operations.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A parameter for processing algorithms which accepts multiple map layers.
static QgsFields indicesToFields(const QList< int > &indices, const QgsFields &fields)
Returns a subset of fields based on the indices of desired fields.
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap(), const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QgsRemappingSinkDefinition *remappingDefinition=nullptr)
Creates a feature sink ready for adding features.
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, QgsProcessingUtils::LayerHint typeHint=QgsProcessingUtils::LayerHint::UnknownType, QgsProcessing::LayerOptionsFlags flags=QgsProcessing::LayerOptionsFlags())
Interprets a string as a map layer within the supplied context.
Represents a vector layer which manages a vector based data sets.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
static Qgis::WkbType multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.
const QgsCoordinateReferenceSystem & crs