QGIS API Documentation 3.99.0-Master (2fe06baccd8)
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
24
25QString QgsMergeVectorAlgorithm::name() const
26{
27 return QStringLiteral( "mergevectorlayers" );
28}
29
30QString QgsMergeVectorAlgorithm::displayName() const
31{
32 return QObject::tr( "Merge vector layers" );
33}
34
35QStringList QgsMergeVectorAlgorithm::tags() const
36{
37 return QObject::tr( "vector,layers,collect,merge,combine" ).split( ',' );
38}
39
40QString QgsMergeVectorAlgorithm::group() const
41{
42 return QObject::tr( "Vector general" );
43}
44
45QString QgsMergeVectorAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorgeneral" );
48}
49
50void QgsMergeVectorAlgorithm::initAlgorithm( const QVariantMap & )
51{
52 addParameter( new QgsProcessingParameterMultipleLayers( QStringLiteral( "LAYERS" ), QObject::tr( "Input layers" ), Qgis::ProcessingSourceType::Vector ) );
53 addParameter( new QgsProcessingParameterCrs( QStringLiteral( "CRS" ), QObject::tr( "Destination CRS" ), QVariant(), true ) );
54 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Merged" ) ) );
55
56 // new boolean parameter to add source layer information
57 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "ADD_SOURCE_FIELDS" ), QObject::tr( "Add source layer information (layer name and path)" ), true ) );
58}
59
60QString QgsMergeVectorAlgorithm::shortDescription() const
61{
62 return QObject::tr( "Combines multiple vector layers of the same geometry type into a single one." );
63}
64
65QString QgsMergeVectorAlgorithm::shortHelpString() const
66{
67 return QObject::tr( "This algorithm combines multiple vector layers of the same geometry type into a single one.\n\n"
68 "The attribute table of the resulting layer will contain the fields from all input layers. "
69 "If fields with the same name but different types are found then the exported field will be automatically converted into a string type field. "
70 "Optionally, new fields storing the original layer name and source can be added.\n\n"
71 "If any input layers contain Z or M values, then the output layer will also contain these values. Similarly, "
72 "if any of the input layers are multi-part, the output layer will also be a multi-part layer.\n\n"
73 "Optionally, the destination coordinate reference system (CRS) for the merged layer can be set. If it is not set, the CRS will be "
74 "taken from the first input layer. All layers will all be reprojected to match this CRS." );
75}
76
77Qgis::ProcessingAlgorithmDocumentationFlags QgsMergeVectorAlgorithm::documentationFlags() const
78{
80}
81
82QgsMergeVectorAlgorithm *QgsMergeVectorAlgorithm::createInstance() const
83{
84 return new QgsMergeVectorAlgorithm();
85}
86
87QVariantMap QgsMergeVectorAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
88{
89 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context );
90
91 const bool addSourceFields = parameterAsBool( parameters, QStringLiteral( "ADD_SOURCE_FIELDS" ), context );
92
93 QgsFields outputFields;
94 long totalFeatureCount = 0;
96 QgsCoordinateReferenceSystem outputCrs = parameterAsCrs( parameters, QStringLiteral( "CRS" ), context );
97
98 if ( outputCrs.isValid() )
99 feedback->pushInfo( QObject::tr( "Using specified destination CRS %1" ).arg( outputCrs.authid() ) );
100
101 bool errored = false;
102
103 // loop through input layers and determine geometry type, crs, fields, total feature count,...
104 long i = 0;
105 for ( QgsMapLayer *layer : layers )
106 {
107 i++;
108
109 if ( feedback->isCanceled() )
110 break;
111
112 if ( !layer )
113 {
114 feedback->pushDebugInfo( QObject::tr( "Error retrieving map layer." ) );
115 errored = true;
116 continue;
117 }
118
119 if ( layer->type() != Qgis::LayerType::Vector )
120 throw QgsProcessingException( QObject::tr( "All layers must be vector layers!" ) );
121
122 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer );
123
124 const Qgis::WkbType layerWkbType = vl->wkbType();
125 const QgsCoordinateReferenceSystem layerCrs = vl->crs();
126 const QString layerName = vl->name();
127
128 if ( !outputCrs.isValid() && layerCrs.isValid() )
129 {
130 outputCrs = layerCrs;
131 feedback->pushInfo( QObject::tr( "Taking destination CRS %1 from layer" ).arg( outputCrs.authid() ) );
132 }
133
134 // check wkb type
135 if ( outputType != Qgis::WkbType::Unknown && outputType != Qgis::WkbType::NoGeometry )
136 {
137 if ( QgsWkbTypes::geometryType( outputType ) != QgsWkbTypes::geometryType( layerWkbType ) )
138 throw QgsProcessingException( QObject::tr( "All layers must have same geometry type! Encountered a %1 layer when expecting a %2 layer." )
140
141 if ( QgsWkbTypes::hasM( layerWkbType ) && !QgsWkbTypes::hasM( outputType ) )
142 {
143 outputType = QgsWkbTypes::addM( outputType );
144 feedback->pushInfo( QObject::tr( "Found a layer with M values, upgrading output type to %1" ).arg( QgsWkbTypes::displayString( outputType ) ) );
145 }
146 if ( QgsWkbTypes::hasZ( layerWkbType ) && !QgsWkbTypes::hasZ( outputType ) )
147 {
148 outputType = QgsWkbTypes::addZ( outputType );
149 feedback->pushInfo( QObject::tr( "Found a layer with Z values, upgrading output type to %1" ).arg( QgsWkbTypes::displayString( outputType ) ) );
150 }
151 if ( QgsWkbTypes::isMultiType( layerWkbType ) && !QgsWkbTypes::isMultiType( outputType ) )
152 {
153 outputType = QgsWkbTypes::multiType( outputType );
154 feedback->pushInfo( QObject::tr( "Found a layer with multiparts, upgrading output type to %1" ).arg( QgsWkbTypes::displayString( outputType ) ) );
155 }
156 }
157 else
158 {
159 outputType = layerWkbType;
160 feedback->pushInfo( QObject::tr( "Setting output type to %1" ).arg( QgsWkbTypes::displayString( outputType ) ) );
161 }
162
163 totalFeatureCount += vl->featureCount();
164
165 // check field type
166 for ( const QgsField &sourceField : vl->fields() )
167 {
168 bool found = false;
169 for ( QgsField &destField : outputFields )
170 {
171 if ( destField.name().compare( sourceField.name(), Qt::CaseInsensitive ) == 0 )
172 {
173 found = true;
174 if ( destField.type() != sourceField.type() )
175 {
176 feedback->pushWarning( QObject::tr( "%1 field in layer %2 has different data type than the destination layer (%3 instead of %4). "
177 "%1 field will be converted to string type." )
178 .arg( sourceField.name(), layerName, sourceField.typeName(), destField.typeName() ) );
179 destField.setType( QMetaType::Type::QString );
180 destField.setSubType( QMetaType::Type::UnknownType );
181 destField.setLength( 0 );
182 destField.setPrecision( 0 );
183 }
184 else if ( destField.type() == QMetaType::Type::QString && destField.length() < sourceField.length() )
185 {
186 feedback->pushWarning( QObject::tr( "%1 field in layer %2 has different field length than the destination layer (%3 vs %4). "
187 "%1 field length will be extended to match the larger of the two." )
188 .arg( sourceField.name(), layerName, QString::number( sourceField.length() ), QString::number( destField.length() ) ) );
189 destField.setLength( sourceField.length() );
190 }
191 else if ( destField.type() == QMetaType::Type::Double && destField.precision() < sourceField.precision() )
192 {
193 feedback->pushWarning( QObject::tr( "%1 field in layer %2 has different field precision than the destination layer (%3 vs %4). "
194 "%1 field precision will be extended to match the larger of the two." )
195 .arg( sourceField.name(), layerName, QString::number( sourceField.length() ), QString::number( destField.length() ) ) );
196 destField.setPrecision( sourceField.precision() );
197 }
198 break;
199 }
200 }
201
202 if ( !found )
203 outputFields.append( sourceField );
204 }
205 }
206
207 bool addLayerField = false;
208 bool addPathField = false;
209 if ( addSourceFields ) // add source layer information
210 {
211 if ( outputFields.lookupField( QStringLiteral( "layer" ) ) < 0 )
212 {
213 outputFields.append( QgsField( QStringLiteral( "layer" ), QMetaType::Type::QString, QString() ) );
214 addLayerField = true;
215 }
216
217 if ( outputFields.lookupField( QStringLiteral( "path" ) ) < 0 )
218 {
219 outputFields.append( QgsField( QStringLiteral( "path" ), QMetaType::Type::QString, QString() ) );
220 addPathField = true;
221 }
222 }
223
224 QString dest;
225 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outputFields, outputType, outputCrs, QgsFeatureSink::RegeneratePrimaryKey ) );
226 if ( !sink )
227 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
228
229 const bool hasZ = QgsWkbTypes::hasZ( outputType );
230 const bool hasM = QgsWkbTypes::hasM( outputType );
231 const bool isMulti = QgsWkbTypes::isMultiType( outputType );
232 const double step = totalFeatureCount > 0 ? 100.0 / totalFeatureCount : 1;
233 i = 0;
234 int layerNumber = 0;
235 for ( QgsMapLayer *layer : layers )
236 {
237 layerNumber++;
238 if ( !layer )
239 continue;
240
241 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer );
242 if ( !vl )
243 continue;
244
245 const QString layerName = layer->name();
246 const QString layerSource = layer->publicSource();
247 const QgsFields layerFields = vl->fields();
248
249 feedback->pushInfo( QObject::tr( "Packaging layer %1/%2: %3" ).arg( layerNumber ).arg( layers.count() ).arg( layerName ) );
250
251 QgsFeatureIterator it = vl->getFeatures( QgsFeatureRequest().setDestinationCrs( outputCrs, context.transformContext() ) );
252 QgsFeature f;
253 while ( it.nextFeature( f ) )
254 {
255 if ( feedback->isCanceled() )
256 break;
257
258 // ensure feature geometry is of correct type
259 if ( f.hasGeometry() )
260 {
261 bool changed = false;
262 QgsGeometry g = f.geometry();
263 if ( hasZ && !g.constGet()->is3D() )
264 {
265 g.get()->addZValue( 0 );
266 changed = true;
267 }
268 if ( hasM && !g.constGet()->isMeasure() )
269 {
270 g.get()->addMValue( 0 );
271 changed = true;
272 }
273 if ( isMulti && !g.isMultipart() )
274 {
276 changed = true;
277 }
278 if ( changed )
279 f.setGeometry( g );
280 }
281
282 // process feature attributes
283 QgsAttributes destAttributes;
284 for ( const QgsField &destField : outputFields )
285 {
286 if ( addLayerField && destField.name() == QLatin1String( "layer" ) )
287 {
288 destAttributes.append( layerName );
289 continue;
290 }
291 else if ( addPathField && destField.name() == QLatin1String( "path" ) )
292 {
293 destAttributes.append( layerSource );
294 continue;
295 }
296
297 QVariant destAttribute;
298 const int sourceIndex = layerFields.lookupField( destField.name() );
299 if ( sourceIndex >= 0 )
300 {
301 destAttribute = f.attributes().at( sourceIndex );
302 }
303 destAttributes.append( destAttribute );
304 }
305 f.setAttributes( destAttributes );
306
307 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
308 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
309 i += 1;
310 feedback->setProgress( i * step );
311 }
312 }
313
314 if ( errored )
315 throw QgsProcessingException( QObject::tr( "Error obtained while merging one or more layers." ) );
316
317 sink->finalize();
318
319 QVariantMap outputs;
320 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
321 return outputs;
322}
323
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3539
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3619
@ Vector
Vector layer.
Definition qgis.h:191
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:277
@ NoGeometry
No geometry.
Definition qgis.h:294
@ Unknown
Unknown.
Definition qgis.h:278
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:58
QgsAttributes attributes
Definition qgsfeature.h:67
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
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:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
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:80
QString name
Definition qgsmaplayer.h:84
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:87
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.