QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmmergevector.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmmergevector.cpp
3 ------------------
4 begin : December 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson 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
21#include "qgsvectorlayer.h"
22
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29QString QgsMergeVectorAlgorithm::name() const
30{
31 return u"mergevectorlayers"_s;
32}
33
34QString QgsMergeVectorAlgorithm::displayName() const
35{
36 return QObject::tr( "Merge vector layers" );
37}
38
39QStringList QgsMergeVectorAlgorithm::tags() const
40{
41 return QObject::tr( "vector,layers,collect,merge,combine" ).split( ',' );
42}
43
44QString QgsMergeVectorAlgorithm::group() const
45{
46 return QObject::tr( "Vector general" );
47}
48
49QString QgsMergeVectorAlgorithm::groupId() const
50{
51 return u"vectorgeneral"_s;
52}
53
54void QgsMergeVectorAlgorithm::initAlgorithm( const QVariantMap & )
55{
56 addParameter( new QgsProcessingParameterMultipleLayers( u"LAYERS"_s, QObject::tr( "Input layers" ), Qgis::ProcessingSourceType::Vector ) );
57 addParameter( new QgsProcessingParameterCrs( u"CRS"_s, QObject::tr( "Destination CRS" ), QVariant(), true ) );
58 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Merged" ) ) );
59
60 // new boolean parameter to add source layer information
61 addParameter( new QgsProcessingParameterBoolean( u"ADD_SOURCE_FIELDS"_s, QObject::tr( "Add source layer information (layer name and path)" ), true ) );
62}
63
64QString QgsMergeVectorAlgorithm::shortDescription() const
65{
66 return QObject::tr( "Combines multiple vector layers of the same geometry type into a single one." );
67}
68
69QString QgsMergeVectorAlgorithm::shortHelpString() const
70{
71 return QObject::tr( "This algorithm combines multiple vector layers of the same geometry type into a single one.\n\n"
72 "The attribute table of the resulting layer will contain the fields from all input layers. "
73 "If fields with the same name but different types are found then the exported field will be automatically converted into a string type field. "
74 "Optionally, new fields storing the original layer name and source can be added.\n\n"
75 "If any input layers contain Z or M values, then the output layer will also contain these values. Similarly, "
76 "if any of the input layers are multi-part, the output layer will also be a multi-part layer.\n\n"
77 "Optionally, the destination coordinate reference system (CRS) for the merged layer can be set. If it is not set, the CRS will be "
78 "taken from the first input layer. All layers will all be reprojected to match this CRS." );
79}
80
81Qgis::ProcessingAlgorithmDocumentationFlags QgsMergeVectorAlgorithm::documentationFlags() const
82{
84}
85
86QgsMergeVectorAlgorithm *QgsMergeVectorAlgorithm::createInstance() const
87{
88 return new QgsMergeVectorAlgorithm();
89}
90
91QVariantMap QgsMergeVectorAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
92{
93 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
94
95 const bool addSourceFields = parameterAsBool( parameters, u"ADD_SOURCE_FIELDS"_s, context );
96
97 QgsFields outputFields;
98 long totalFeatureCount = 0;
100 QgsCoordinateReferenceSystem outputCrs = parameterAsCrs( parameters, u"CRS"_s, context );
101
102 if ( outputCrs.isValid() )
103 feedback->pushInfo( QObject::tr( "Using specified destination CRS %1" ).arg( outputCrs.authid() ) );
104
105 bool errored = false;
106
107 // loop through input layers and determine geometry type, crs, fields, total feature count,...
108 long i = 0;
109 for ( QgsMapLayer *layer : layers )
110 {
111 i++;
112
113 if ( feedback->isCanceled() )
114 break;
115
116 if ( !layer )
117 {
118 feedback->pushDebugInfo( QObject::tr( "Error retrieving map layer." ) );
119 errored = true;
120 continue;
121 }
122
123 if ( layer->type() != Qgis::LayerType::Vector )
124 throw QgsProcessingException( QObject::tr( "All layers must be vector layers!" ) );
125
126 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer );
127
128 const Qgis::WkbType layerWkbType = vl->wkbType();
129 const QgsCoordinateReferenceSystem layerCrs = vl->crs();
130 const QString layerName = vl->name();
131
132 if ( !outputCrs.isValid() && layerCrs.isValid() )
133 {
134 outputCrs = layerCrs;
135 feedback->pushInfo( QObject::tr( "Taking destination CRS %1 from layer" ).arg( outputCrs.authid() ) );
136 }
137
138 // check wkb type
139 if ( outputType != Qgis::WkbType::Unknown && outputType != Qgis::WkbType::NoGeometry )
140 {
141 if ( QgsWkbTypes::geometryType( outputType ) != QgsWkbTypes::geometryType( layerWkbType ) )
142 throw QgsProcessingException( QObject::tr( "All layers must have same geometry type! Encountered a %1 layer when expecting a %2 layer." )
144
145 if ( QgsWkbTypes::hasM( layerWkbType ) && !QgsWkbTypes::hasM( outputType ) )
146 {
147 outputType = QgsWkbTypes::addM( outputType );
148 feedback->pushInfo( QObject::tr( "Found a layer with M values, upgrading output type to %1" ).arg( QgsWkbTypes::displayString( outputType ) ) );
149 }
150 if ( QgsWkbTypes::hasZ( layerWkbType ) && !QgsWkbTypes::hasZ( outputType ) )
151 {
152 outputType = QgsWkbTypes::addZ( outputType );
153 feedback->pushInfo( QObject::tr( "Found a layer with Z values, upgrading output type to %1" ).arg( QgsWkbTypes::displayString( outputType ) ) );
154 }
155 if ( QgsWkbTypes::isMultiType( layerWkbType ) && !QgsWkbTypes::isMultiType( outputType ) )
156 {
157 outputType = QgsWkbTypes::multiType( outputType );
158 feedback->pushInfo( QObject::tr( "Found a layer with multiparts, upgrading output type to %1" ).arg( QgsWkbTypes::displayString( outputType ) ) );
159 }
160 }
161 else
162 {
163 outputType = layerWkbType;
164 feedback->pushInfo( QObject::tr( "Setting output type to %1" ).arg( QgsWkbTypes::displayString( outputType ) ) );
165 }
166
167 totalFeatureCount += vl->featureCount();
168
169 // check field type
170 for ( const QgsField &sourceField : vl->fields() )
171 {
172 bool found = false;
173 for ( QgsField &destField : outputFields )
174 {
175 if ( destField.name().compare( sourceField.name(), Qt::CaseInsensitive ) == 0 )
176 {
177 found = true;
178 if ( destField.type() != sourceField.type() )
179 {
180 feedback->pushWarning( QObject::tr( "%1 field in layer %2 has different data type than the destination layer (%3 instead of %4). "
181 "%1 field will be converted to string type." )
182 .arg( sourceField.name(), layerName, sourceField.typeName(), destField.typeName() ) );
183 destField.setType( QMetaType::Type::QString );
184 destField.setSubType( QMetaType::Type::UnknownType );
185 destField.setLength( 0 );
186 destField.setPrecision( 0 );
187 }
188 else if ( destField.type() == QMetaType::Type::QString && destField.length() < sourceField.length() )
189 {
190 feedback->pushWarning( QObject::tr( "%1 field in layer %2 has different field length than the destination layer (%3 vs %4). "
191 "%1 field length will be extended to match the larger of the two." )
192 .arg( sourceField.name(), layerName, QString::number( sourceField.length() ), QString::number( destField.length() ) ) );
193 destField.setLength( sourceField.length() );
194 }
195 else if ( destField.type() == QMetaType::Type::Double && destField.precision() < sourceField.precision() )
196 {
197 feedback->pushWarning( QObject::tr( "%1 field in layer %2 has different field precision than the destination layer (%3 vs %4). "
198 "%1 field precision will be extended to match the larger of the two." )
199 .arg( sourceField.name(), layerName, QString::number( sourceField.length() ), QString::number( destField.length() ) ) );
200 destField.setPrecision( sourceField.precision() );
201 }
202 break;
203 }
204 }
205
206 if ( !found )
207 outputFields.append( sourceField );
208 }
209 }
210
211 bool addLayerField = false;
212 bool addPathField = false;
213 if ( addSourceFields ) // add source layer information
214 {
215 if ( outputFields.lookupField( u"layer"_s ) < 0 )
216 {
217 outputFields.append( QgsField( u"layer"_s, QMetaType::Type::QString, QString() ) );
218 addLayerField = true;
219 }
220
221 if ( outputFields.lookupField( u"path"_s ) < 0 )
222 {
223 outputFields.append( QgsField( u"path"_s, QMetaType::Type::QString, QString() ) );
224 addPathField = true;
225 }
226 }
227
228 QString dest;
229 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, outputFields, outputType, outputCrs, QgsFeatureSink::RegeneratePrimaryKey ) );
230 if ( !sink )
231 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
232
233 const bool hasZ = QgsWkbTypes::hasZ( outputType );
234 const bool hasM = QgsWkbTypes::hasM( outputType );
235 const bool isMulti = QgsWkbTypes::isMultiType( outputType );
236 const double step = totalFeatureCount > 0 ? 100.0 / totalFeatureCount : 1;
237 i = 0;
238 int layerNumber = 0;
239 for ( QgsMapLayer *layer : layers )
240 {
241 layerNumber++;
242 if ( !layer )
243 continue;
244
245 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer );
246 if ( !vl )
247 continue;
248
249 const QString layerName = layer->name();
250 const QString layerSource = layer->publicSource();
251 const QgsFields layerFields = vl->fields();
252
253 feedback->pushInfo( QObject::tr( "Packaging layer %1/%2: %3" ).arg( layerNumber ).arg( layers.count() ).arg( layerName ) );
254
255 QgsFeatureIterator it = vl->getFeatures( QgsFeatureRequest().setDestinationCrs( outputCrs, context.transformContext() ) );
256 QgsFeature f;
257 while ( it.nextFeature( f ) )
258 {
259 if ( feedback->isCanceled() )
260 break;
261
262 // ensure feature geometry is of correct type
263 if ( f.hasGeometry() )
264 {
265 bool changed = false;
266 QgsGeometry g = f.geometry();
267 if ( hasZ && !g.constGet()->is3D() )
268 {
269 g.get()->addZValue( 0 );
270 changed = true;
271 }
272 if ( hasM && !g.constGet()->isMeasure() )
273 {
274 g.get()->addMValue( 0 );
275 changed = true;
276 }
277 if ( isMulti && !g.isMultipart() )
278 {
280 changed = true;
281 }
282 if ( changed )
283 f.setGeometry( g );
284 }
285
286 // process feature attributes
287 QgsAttributes destAttributes;
288 for ( const QgsField &destField : outputFields )
289 {
290 if ( addLayerField && destField.name() == "layer"_L1 )
291 {
292 destAttributes.append( layerName );
293 continue;
294 }
295 else if ( addPathField && destField.name() == "path"_L1 )
296 {
297 destAttributes.append( layerSource );
298 continue;
299 }
300
301 QVariant destAttribute;
302 const int sourceIndex = layerFields.lookupField( destField.name() );
303 if ( sourceIndex >= 0 )
304 {
305 destAttribute = f.attributes().at( sourceIndex );
306 }
307 destAttributes.append( destAttribute );
308 }
309 f.setAttributes( destAttributes );
310
311 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
312 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
313 i += 1;
314 feedback->setProgress( i * step );
315 }
316 }
317
318 if ( errored )
319 throw QgsProcessingException( QObject::tr( "Error obtained while merging one or more layers." ) );
320
321 sink->finalize();
322
323 QVariantMap outputs;
324 outputs.insert( u"OUTPUT"_s, dest );
325 return outputs;
326}
327
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3610
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3690
@ Vector
Vector layer.
Definition qgis.h:194
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3701
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:280
@ NoGeometry
No geometry.
Definition qgis.h:298
@ Unknown
Unknown.
Definition qgis.h:281
virtual bool addZValue(double zValue=0)=0
Adds a z-dimension to the geometry, initialized to a preset value.
bool isMeasure() const
Returns true if the geometry contains m values.
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
virtual bool addMValue(double mValue=0)=0
Adds a measure to the geometry, initialized to a preset value.
A vector of attributes.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:69
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:46
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
A geometry is the spatial representation of a feature.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
Base class for all map layer types.
Definition qgsmaplayer.h:83
QString name
Definition qgsmaplayer.h:87
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
virtual void pushDebugInfo(const QString &info)
Pushes an informational message containing debugging helpers from the algorithm.
A boolean parameter for processing algorithms.
A coordinate reference system parameter for processing algorithms.
A feature sink output for processing algorithms.
A parameter for processing algorithms which accepts multiple map layers.
Represents a vector layer which manages a vector based dataset.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
Q_INVOKABLE Qgis::WkbType wkbType() const final
Returns the WKBType or WKBUnknown in case of error.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const final
Queries the layer for features specified in request.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Q_INVOKABLE QString displayString(Qgis::WkbType type)
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
static Qgis::WkbType addM(Qgis::WkbType type)
Adds the m dimension to a WKB type and returns the new type.
static Qgis::WkbType addZ(Qgis::WkbType type)
Adds the z dimension to a WKB type and returns the new type.
static Q_INVOKABLE bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static Q_INVOKABLE bool hasM(Qgis::WkbType type)
Tests whether a WKB type contains m values.
static Q_INVOKABLE QString geometryDisplayString(Qgis::GeometryType type)
Returns a display string for a geometry type.
static Qgis::WkbType multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.
static Q_INVOKABLE bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.