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