QGIS API Documentation 3.41.0-Master (cea29feecf2)
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
128 QString dest;
129 sink.reset( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outputFields, geometryType, crs, QgsFeatureSink::RegeneratePrimaryKey ) );
130 if ( !sink )
131 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
132
133 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
134
135 const long total = sourceA->featureCount();
136 QgsOverlayUtils::intersection( *sourceA, *overlayLayer, *sink, context, feedback, count, total, fieldIndicesA, fieldIndicesB );
137
138 sink->finalize();
139 }
140 else
141 {
142 QgsProcessingMultiStepFeedback multiStepFeedback( totalLayerCount, feedback );
143 QgsVectorLayer *intersectionLayer = nullptr;
144
145 long i = 0;
146 for ( QgsMapLayer *layer : layers )
147 {
148 if ( feedback->isCanceled() )
149 break;
150
151 multiStepFeedback.setCurrentStep( i );
152
153 if ( !layer )
154 continue;
155
156 QgsVectorLayer *overlayLayer = qobject_cast<QgsVectorLayer *>( layer );
157 if ( !overlayLayer )
158 continue;
159
160 count = 0;
161 if ( i == 0 )
162 {
163 fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), sourceA->fields() );
164 fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), overlayLayer->fields() );
165
167 QgsProcessingUtils::indicesToFields( fieldIndicesA, sourceA->fields() ),
168 QgsProcessingUtils::indicesToFields( fieldIndicesB, overlayLayer->fields() ),
169 overlayFieldsPrefix
170 );
171
172 QString id = QStringLiteral( "memory:" );
173 sink.reset( QgsProcessingUtils::createFeatureSink( id, context, outputFields, geometryType, crs ) );
174 QgsOverlayUtils::intersection( *sourceA, *overlayLayer, *sink, context, &multiStepFeedback, count, sourceA->featureCount(), fieldIndicesA, fieldIndicesB );
175
176 intersectionLayer = qobject_cast<QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( id, context ) );
177 }
178 else if ( i == totalLayerCount - 1 )
179 {
180 fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), intersectionLayer->fields() );
181 fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), overlayLayer->fields() );
182
184 QgsProcessingUtils::indicesToFields( fieldIndicesA, intersectionLayer->fields() ),
185 QgsProcessingUtils::indicesToFields( fieldIndicesB, overlayLayer->fields() ),
186 overlayFieldsPrefix
187 );
188
189 QString dest;
190 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outputFields, geometryType, crs ) );
191 if ( !sink )
192 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
193
194 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
195
196 QgsOverlayUtils::intersection( *intersectionLayer, *overlayLayer, *sink, context, &multiStepFeedback, count, intersectionLayer->featureCount(), fieldIndicesA, fieldIndicesB );
197 }
198 else
199 {
200 fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), intersectionLayer->fields() );
201 fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), overlayLayer->fields() );
202
204 QgsProcessingUtils::indicesToFields( fieldIndicesA, intersectionLayer->fields() ),
205 QgsProcessingUtils::indicesToFields( fieldIndicesB, overlayLayer->fields() ),
206 overlayFieldsPrefix
207 );
208
209 QString id = QStringLiteral( "memory:" );
210 sink.reset( QgsProcessingUtils::createFeatureSink( id, context, outputFields, geometryType, crs ) );
211 QgsOverlayUtils::intersection( *intersectionLayer, *overlayLayer, *sink, context, &multiStepFeedback, count, intersectionLayer->featureCount(), fieldIndicesA, fieldIndicesB );
212
213 intersectionLayer = qobject_cast<QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( id, context ) );
214 }
215
216 i++;
217 }
218 }
219
220 return outputs;
221}
222
@ 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:3412
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