28QString QgsJoinByNearestAlgorithm::name()
const
30 return QStringLiteral(
"joinbynearest" );
33QString QgsJoinByNearestAlgorithm::displayName()
const
35 return QObject::tr(
"Join attributes by nearest" );
38QStringList QgsJoinByNearestAlgorithm::tags()
const
40 return QObject::tr(
"join,connect,attributes,values,fields,tables,proximity,closest,neighbour,neighbor,n-nearest,distance" ).split(
',' );
43QString QgsJoinByNearestAlgorithm::group()
const
45 return QObject::tr(
"Vector general" );
48QString QgsJoinByNearestAlgorithm::groupId()
const
50 return QStringLiteral(
"vectorgeneral" );
53void QgsJoinByNearestAlgorithm::initAlgorithm(
const QVariantMap & )
60 addParameter(
new QgsProcessingParameterBoolean( QStringLiteral(
"DISCARD_NONMATCHING" ), QObject::tr(
"Discard records which could not be joined" ),
false ) );
62 addParameter(
new QgsProcessingParameterString( QStringLiteral(
"PREFIX" ), QObject::tr(
"Joined field prefix" ), QVariant(),
false,
true ) );
66 addParameter(
new QgsProcessingParameterDistance( QStringLiteral(
"MAX_DISTANCE" ), QObject::tr(
"Maximum distance" ), QVariant(), QStringLiteral(
"INPUT" ),
true, 0 ) );
70 auto nonMatchingSink = std::make_unique<QgsProcessingParameterFeatureSink>(
75 addParameter( nonMatchingSink.release() );
77 addOutput(
new QgsProcessingOutputNumber( QStringLiteral(
"JOINED_COUNT" ), QObject::tr(
"Number of joined features from input table" ) ) );
78 addOutput(
new QgsProcessingOutputNumber( QStringLiteral(
"UNJOINABLE_COUNT" ), QObject::tr(
"Number of unjoinable features from input table" ) ) );
81QString QgsJoinByNearestAlgorithm::shortHelpString()
const
83 return QObject::tr(
"This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the "
84 "input one, with additional attributes in its attribute table.\n\n"
85 "The additional attributes and their values are taken from a second vector layer, where features are joined "
86 "by finding the closest features from each layer. By default only the single nearest feature is joined,"
87 "but optionally the join can use the n-nearest neighboring features instead. If multiple features are found "
88 "with identical distances these will all be returned (even if the total number of features exceeds the specified "
89 "maximum feature count).\n\n"
90 "If a maximum distance is specified, then only features which are closer than this distance "
91 "will be matched.\n\n"
92 "The output features will contain the selected attributes from the nearest feature, "
93 "along with new attributes for the distance to the near feature, the index of the feature, "
94 "and the coordinates of the closest point on the input feature (feature_x, feature_y) "
95 "to the matched nearest feature, and the coordinates of the closet point on the matched feature "
96 "(nearest_x, nearest_y).\n\n"
97 "This algorithm uses purely Cartesian calculations for distance, and does not consider "
98 "geodetic or ellipsoid properties when determining feature proximity." );
101QString QgsJoinByNearestAlgorithm::shortDescription()
const
103 return QObject::tr(
"Joins a layer to another layer, using the closest features (nearest neighbors)." );
111QgsJoinByNearestAlgorithm *QgsJoinByNearestAlgorithm::createInstance()
const
113 return new QgsJoinByNearestAlgorithm();
118 const int neighbors = parameterAsInt( parameters, QStringLiteral(
"NEIGHBORS" ), context );
119 const bool discardNonMatching = parameterAsBoolean( parameters, QStringLiteral(
"DISCARD_NONMATCHING" ), context );
120 const double maxDistance = parameters.value( QStringLiteral(
"MAX_DISTANCE" ) ).isValid() ? parameterAsDouble( parameters, QStringLiteral(
"MAX_DISTANCE" ), context ) : std::numeric_limits<double>::quiet_NaN();
121 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral(
"INPUT" ), context ) );
125 std::unique_ptr<QgsProcessingFeatureSource> input2( parameterAsSource( parameters, QStringLiteral(
"INPUT_2" ), context ) );
129 const bool sameSourceAndTarget = parameters.value( QStringLiteral(
"INPUT" ) ) == parameters.value( QStringLiteral(
"INPUT_2" ) );
131 const QString prefix = parameterAsString( parameters, QStringLiteral(
"PREFIX" ), context );
132 const QStringList fieldsToCopy = parameterAsStrings( parameters, QStringLiteral(
"FIELDS_TO_COPY" ), context );
136 if ( fieldsToCopy.empty() )
138 outFields2 = input2->fields();
139 fields2Indices.reserve( outFields2.
count() );
140 for (
int i = 0; i < outFields2.
count(); ++i )
147 fields2Indices.reserve( fieldsToCopy.count() );
148 for (
const QString &field : fieldsToCopy )
150 const int index = input2->fields().lookupField( field );
153 fields2Indices << index;
154 outFields2.
append( input2->fields().at( index ) );
159 if ( !prefix.isEmpty() )
161 for (
int i = 0; i < outFields2.
count(); ++i )
163 outFields2.
rename( i, prefix + outFields2[i].name() );
172 resultFields.
append(
QgsField( QStringLiteral(
"n" ), QMetaType::Type::Int ) );
173 resultFields.
append(
QgsField( QStringLiteral(
"distance" ), QMetaType::Type::Double ) );
174 resultFields.
append(
QgsField( QStringLiteral(
"feature_x" ), QMetaType::Type::Double ) );
175 resultFields.
append(
QgsField( QStringLiteral(
"feature_y" ), QMetaType::Type::Double ) );
176 resultFields.
append(
QgsField( QStringLiteral(
"nearest_x" ), QMetaType::Type::Double ) );
177 resultFields.
append(
QgsField( QStringLiteral(
"nearest_y" ), QMetaType::Type::Double ) );
181 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT" ), context, dest, outFields, input->wkbType(), input->sourceCrs(),
QgsFeatureSink::RegeneratePrimaryKey ) );
182 if ( parameters.value( QStringLiteral(
"OUTPUT" ) ).isValid() && !sink )
185 QString destNonMatching1;
186 std::unique_ptr<QgsFeatureSink> sinkNonMatching1( parameterAsSink( parameters, QStringLiteral(
"NON_MATCHING" ), context, destNonMatching1, input->fields(), input->wkbType(), input->sourceCrs(),
QgsFeatureSink::RegeneratePrimaryKey ) );
187 if ( parameters.value( QStringLiteral(
"NON_MATCHING" ) ).isValid() && !sinkNonMatching1 )
192 QHash<QgsFeatureId, QgsAttributes> input2AttributeCache;
193 double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1;
207 for (
int field2Index : fields2Indices )
209 attributes << f.
attribute( field2Index );
211 input2AttributeCache.insert( f.
id(), attributes );
219 nullMatch.reserve( fields2Indices.size() + 6 );
220 for (
int i = 0; i < fields2Indices.count() + 6; ++i )
221 nullMatch << QVariant();
223 long long joinedCount = 0;
224 long long unjoinedCount = 0;
227 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
240 if ( !f.hasGeometry() )
243 if ( sinkNonMatching1 )
246 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral(
"NON_MATCHING" ) ) );
248 if ( sink && !discardNonMatching )
251 attr.append( nullMatch );
252 f.setAttributes( attr );
263 const double searchDistance = std::isnan( maxDistance ) ? 0 : std::max( std::numeric_limits<double>::min(), maxDistance );
264 const QList<QgsFeatureId> nearest = index.nearestNeighbor( f.geometry(), neighbors + ( sameSourceAndTarget ? 1 : 0 ), searchDistance );
266 if ( nearest.count() > neighbors + ( sameSourceAndTarget ? 1 : 0 ) )
268 feedback->
pushInfo( QObject::tr(
"Multiple matching features found at same distance from search feature, found %n feature(s) instead of %1",
nullptr, nearest.count() - ( sameSourceAndTarget ? 1 : 0 ) ).arg( neighbors ) );
275 if ( sameSourceAndTarget &&
id == f.id() )
281 attr.append( input2AttributeCache.value(
id ) );
287 attr.append( line->length() );
288 attr.append( line->startPoint().x() );
289 attr.append( line->startPoint().y() );
290 attr.append( line->endPoint().x() );
291 attr.append( line->endPoint().y() );
295 attr.append( QVariant() );
296 attr.append( QVariant() );
297 attr.append( QVariant() );
298 attr.append( QVariant() );
299 attr.append( QVariant() );
310 if ( sinkNonMatching1 )
313 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral(
"NON_MATCHING" ) ) );
315 if ( !discardNonMatching && sink )
318 attr.append( nullMatch );
319 f.setAttributes( attr );
329 outputs.insert( QStringLiteral(
"JOINED_COUNT" ), joinedCount );
330 outputs.insert( QStringLiteral(
"UNJOINABLE_COUNT" ), unjoinedCount );
334 outputs.insert( QStringLiteral(
"OUTPUT" ), dest );
336 if ( sinkNonMatching1 )
338 sinkNonMatching1->finalize();
339 outputs.insert( QStringLiteral(
"NON_MATCHING" ), destNonMatching1 );
@ VectorAnyGeometry
Any vector layer with geometry.
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
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).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
@ 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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
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.
QgsGeometry shortestLine(const QgsGeometry &other) const
Returns the shortest line joining this geometry to another geometry.
Line string geometry type, with support for z-dimension and m-values.
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.
A numeric output for processing algorithms.
A boolean parameter for processing algorithms.
A double numeric parameter for distance 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 numeric 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).
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
T qgsgeometry_cast(QgsAbstractGeometry *geom)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QList< int > QgsAttributeList