29void QgsJoinByLocationAlgorithm::initAlgorithm(
const QVariantMap & )
34 std::unique_ptr< QgsProcessingParameterEnum > predicateParam = std::make_unique< QgsProcessingParameterEnum >( QStringLiteral(
"PREDICATE" ), QObject::tr(
"Features they (geometric predicate)" ), translatedPredicates(),
true, 0 );
35 QVariantMap predicateMetadata;
36 QVariantMap widgetMetadata;
37 widgetMetadata.insert( QStringLiteral(
"useCheckBoxes" ),
true );
38 widgetMetadata.insert( QStringLiteral(
"columns" ), 2 );
39 predicateMetadata.insert( QStringLiteral(
"widget_wrapper" ), widgetMetadata );
40 predicateParam->setMetadata( predicateMetadata );
41 addParameter( predicateParam.release() );
45 QObject::tr(
"Fields to add (leave empty to use all fields)" ),
48 QStringList joinMethods;
49 joinMethods << QObject::tr(
"Create separate feature for each matching feature (one-to-many)" )
50 << QObject::tr(
"Take attributes of the first matching feature only (one-to-one)" )
51 << QObject::tr(
"Take attributes of the feature with largest overlap only (one-to-one)" );
53 QObject::tr(
"Join type" ),
54 joinMethods,
false,
static_cast< int >( OneToMany ) ) );
56 QObject::tr(
"Discard records which could not be joined" ),
59 QObject::tr(
"Joined field prefix" ), QVariant(),
false,
true ) );
62 addOutput(
new QgsProcessingOutputNumber( QStringLiteral(
"JOINED_COUNT" ), QObject::tr(
"Number of joined features from input table" ) ) );
65QString QgsJoinByLocationAlgorithm::name()
const
67 return QStringLiteral(
"joinattributesbylocation" );
70QString QgsJoinByLocationAlgorithm::displayName()
const
72 return QObject::tr(
"Join attributes by location" );
75QStringList QgsJoinByLocationAlgorithm::tags()
const
77 return QObject::tr(
"join,intersects,intersecting,touching,within,contains,overlaps,relation,spatial" ).split(
',' );
80QString QgsJoinByLocationAlgorithm::group()
const
82 return QObject::tr(
"Vector general" );
85QString QgsJoinByLocationAlgorithm::groupId()
const
87 return QStringLiteral(
"vectorgeneral" );
90QString QgsJoinByLocationAlgorithm::shortHelpString()
const
92 return QObject::tr(
"This algorithm takes an input vector layer and creates a new vector layer "
93 "that is an extended version of the input one, with additional attributes in its attribute table.\n\n"
94 "The additional attributes and their values are taken from a second vector layer. "
95 "A spatial criteria is applied to select the values from the second layer that are added "
96 "to each feature from the first layer in the resulting one." );
99QString QgsJoinByLocationAlgorithm::shortDescription()
const
101 return QObject::tr(
"Join attributes from one vector layer to another by location." );
104QgsJoinByLocationAlgorithm *QgsJoinByLocationAlgorithm::createInstance()
const
106 return new QgsJoinByLocationAlgorithm();
109QStringList QgsJoinByLocationAlgorithm::translatedPredicates()
111 return { QObject::tr(
"intersect" ),
112 QObject::tr(
"contain" ),
113 QObject::tr(
"equal" ),
114 QObject::tr(
"touch" ),
115 QObject::tr(
"overlap" ),
116 QObject::tr(
"are within" ),
117 QObject::tr(
"cross" ) };
122 mBaseSource.reset( parameterAsSource( parameters, QStringLiteral(
"INPUT" ), context ) );
126 mJoinSource.reset( parameterAsSource( parameters, QStringLiteral(
"JOIN" ), context ) );
130 mJoinMethod =
static_cast< JoinMethod
>( parameterAsEnum( parameters, QStringLiteral(
"METHOD" ), context ) );
132 const QStringList joinedFieldNames = parameterAsStrings( parameters, QStringLiteral(
"JOIN_FIELDS" ), context );
134 mPredicates = parameterAsEnums( parameters, QStringLiteral(
"PREDICATE" ), context );
135 sortPredicates( mPredicates );
137 QString prefix = parameterAsString( parameters, QStringLiteral(
"PREFIX" ), context );
140 if ( joinedFieldNames.empty() )
142 joinFields = mJoinSource->fields();
147 mJoinedFieldIndices.reserve( joinedFieldNames.count() );
148 for (
const QString &field : joinedFieldNames )
150 int index = mJoinSource->fields().lookupField( field );
153 mJoinedFieldIndices << index;
154 joinFields.
append( mJoinSource->fields().at( index ) );
159 if ( !prefix.isEmpty() )
161 for (
int i = 0; i < joinFields.
count(); ++i )
163 joinFields.
rename( i, prefix + joinFields[ i ].name() );
169 QString joinedSinkId;
170 mJoinedFeatures.reset( parameterAsSink( parameters, QStringLiteral(
"OUTPUT" ), context, joinedSinkId, outputFields,
173 if ( parameters.value( QStringLiteral(
"OUTPUT" ) ).isValid() && !mJoinedFeatures )
176 mDiscardNonMatching = parameterAsBoolean( parameters, QStringLiteral(
"DISCARD_NONMATCHING" ), context );
178 QString nonMatchingSinkId;
179 mUnjoinedFeatures.reset( parameterAsSink( parameters, QStringLiteral(
"NON_MATCHING" ), context, nonMatchingSinkId, mBaseSource->fields(),
181 if ( parameters.value( QStringLiteral(
"NON_MATCHING" ) ).isValid() && !mUnjoinedFeatures )
184 switch ( mJoinMethod )
189 if ( mBaseSource->featureCount() > 0 && mJoinSource->featureCount() > 0 && mBaseSource->featureCount() < mJoinSource->featureCount() )
192 processAlgorithmByIteratingOverInputSource( context, feedback );
202 processAlgorithmByIteratingOverJoinedSource( context, feedback );
207 case JoinToLargestOverlap:
208 processAlgorithmByIteratingOverInputSource( context, feedback );
213 if ( mJoinedFeatures )
215 outputs.insert( QStringLiteral(
"OUTPUT" ), joinedSinkId );
217 if ( mUnjoinedFeatures )
219 outputs.insert( QStringLiteral(
"NON_MATCHING" ), nonMatchingSinkId );
223 mJoinedFeatures.reset();
224 mUnjoinedFeatures.reset();
226 outputs.insert( QStringLiteral(
"JOINED_COUNT" ),
static_cast< long long >( mJoinedCount ) );
230bool QgsJoinByLocationAlgorithm::featureFilter(
const QgsFeature &feature,
QgsGeometryEngine *engine,
bool comparingToJoinedFeature,
const QList<int> &predicates )
234 for (
const int predicate : predicates )
247 if ( comparingToJoinedFeature )
256 if ( engine->
within( geom ) )
285 if ( comparingToJoinedFeature )
287 if ( engine->
within( geom ) )
317 feedback->
pushWarning( QObject::tr(
"No spatial index exists for input layer, performance will be severely degraded" ) );
323 const double step = mJoinSource->featureCount() > 0 ? 100.0 / mJoinSource->featureCount() : 1;
330 processFeatureFromJoinSource( f, feedback );
336 if ( !mDiscardNonMatching || mUnjoinedFeatures )
339 unjoinedIds.subtract( mAddedIds );
346 emptyAttributes.reserve( mJoinedFieldIndices.count() );
347 for (
int i = 0; i < mJoinedFieldIndices.count(); ++i )
348 emptyAttributes << QVariant();
355 if ( mJoinedFeatures && !mDiscardNonMatching )
358 attributes.append( emptyAttributes );
360 outputFeature.setAttributes( attributes );
362 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral(
"OUTPUT" ) ) );
365 if ( mUnjoinedFeatures )
368 throw QgsProcessingException( writeFeatureError( mUnjoinedFeatures.get(), QVariantMap(), QStringLiteral(
"NON_MATCHING" ) ) );
377 feedback->
pushWarning( QObject::tr(
"No spatial index exists for join layer, performance will be severely degraded" ) );
382 const double step = mBaseSource->featureCount() > 0 ? 100.0 / mBaseSource->featureCount() : 1;
384 while ( it .nextFeature( f ) )
389 processFeatureFromInputSource( f, context, feedback );
396void QgsJoinByLocationAlgorithm::sortPredicates( QList<int> &predicates )
403 std::sort( predicates.begin(), predicates.end(), [](
int a,
int b ) ->
bool
428 std::unique_ptr< QgsGeometryEngine > engine;
440 switch ( mJoinMethod )
443 if ( mAddedIds.contains( baseFeature.
id() ) )
453 case JoinToLargestOverlap:
454 Q_ASSERT_X(
false,
"QgsJoinByLocationAlgorithm::processFeatureFromJoinSource",
"processFeatureFromJoinSource should not be used with join to largest overlap method" );
460 engine->prepareGeometry();
461 for (
int ix : std::as_const( mJoinedFieldIndices ) )
463 joinAttributes.append( joinFeature.
attribute( ix ) );
466 if ( featureFilter( baseFeature, engine.get(),
false, mPredicates ) )
468 if ( mJoinedFeatures )
471 outputFeature.setAttributes( baseFeature.
attributes() + joinAttributes );
473 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral(
"OUTPUT" ) ) );
478 mAddedIds.insert( baseFeature.
id() );
490 if ( mJoinedFeatures && !mDiscardNonMatching )
493 emptyAttributes.reserve( mJoinedFieldIndices.count() );
494 for (
int i = 0; i < mJoinedFieldIndices.count(); ++i )
495 emptyAttributes << QVariant();
498 attributes.append( emptyAttributes );
500 outputFeature.setAttributes( attributes );
502 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral(
"OUTPUT" ) ) );
505 if ( mUnjoinedFeatures )
508 throw QgsProcessingException( writeFeatureError( mUnjoinedFeatures.get(), QVariantMap(), QStringLiteral(
"NON_MATCHING" ) ) );
515 std::unique_ptr< QgsGeometryEngine > engine;
522 double largestOverlap = std::numeric_limits< double >::lowest();
533 engine->prepareGeometry();
536 if ( featureFilter( joinFeature, engine.get(),
true, mPredicates ) )
538 switch ( mJoinMethod )
542 if ( mJoinedFeatures )
545 joinAttributes.reserve( joinAttributes.size() + mJoinedFieldIndices.size() );
546 for (
int ix : std::as_const( mJoinedFieldIndices ) )
548 joinAttributes.append( joinFeature.
attribute( ix ) );
552 outputFeature.setAttributes( joinAttributes );
554 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral(
"OUTPUT" ) ) );
558 case JoinToLargestOverlap:
561 std::unique_ptr< QgsAbstractGeometry > intersection( engine->intersection( joinFeature.
geometry().
constGet() ) );
566 overlap = intersection->length();
570 overlap = intersection->area();
579 if ( overlap > largestOverlap )
581 largestOverlap = overlap;
582 bestMatch = joinFeature;
590 if ( mJoinMethod == JoinToFirst )
595 switch ( mJoinMethod )
601 case JoinToLargestOverlap:
606 if ( mJoinedFeatures )
609 joinAttributes.reserve( joinAttributes.size() + mJoinedFieldIndices.size() );
610 for (
int ix : std::as_const( mJoinedFieldIndices ) )
612 joinAttributes.append( bestMatch.
attribute( ix ) );
616 outputFeature.setAttributes( joinAttributes );
618 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral(
"OUTPUT" ) ) );
632 if ( mJoinedFeatures && !mDiscardNonMatching )
635 emptyAttributes.reserve( mJoinedFieldIndices.count() );
636 for (
int i = 0; i < mJoinedFieldIndices.count(); ++i )
637 emptyAttributes << QVariant();
640 attributes.append( emptyAttributes );
642 outputFeature.setAttributes( attributes );
644 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral(
"OUTPUT" ) ) );
647 if ( mUnjoinedFeatures )
650 throw QgsProcessingException( writeFeatureError( mUnjoinedFeatures.get(), QVariantMap(), QStringLiteral(
"NON_MATCHING" ) ) );
@ VectorAnyGeometry
Any vector layer with geometry.
@ NotPresent
No spatial index exists for the source.
Abstract base class for all geometries.
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.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
@ 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...
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isValid() const
Returns the validity of this feature.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
QgsAttributeList allAttributesList() const
Utility function to get list of attribute indexes.
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
A geometry engine is a low-level representation of a QgsAbstractGeometry object, optimised for use wi...
virtual bool isEqual(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if this is equal to geom.
virtual bool intersects(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom intersects this.
virtual bool touches(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom touches this.
virtual bool crosses(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom crosses this.
virtual bool overlaps(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom overlaps this.
virtual bool within(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom is within this.
virtual bool contains(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom contains this.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
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 pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
A numeric output for processing algorithms.
A boolean parameter for processing algorithms.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A string parameter for processing algorithms.
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 Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
QSet< QgsFeatureId > QgsFeatureIds