28using namespace Qt::StringLiterals;
32QString QgsJoinByNearestAlgorithm::name()
const
34 return u
"joinbynearest"_s;
37QString QgsJoinByNearestAlgorithm::displayName()
const
39 return QObject::tr(
"Join attributes by nearest" );
42QStringList QgsJoinByNearestAlgorithm::tags()
const
44 return QObject::tr(
"join,connect,attributes,values,fields,tables,proximity,closest,neighbour,neighbor,n-nearest,distance" ).split(
',' );
47QString QgsJoinByNearestAlgorithm::group()
const
49 return QObject::tr(
"Vector general" );
52QString QgsJoinByNearestAlgorithm::groupId()
const
54 return u
"vectorgeneral"_s;
57void QgsJoinByNearestAlgorithm::initAlgorithm(
const QVariantMap & )
64 addParameter(
new QgsProcessingParameterBoolean( u
"DISCARD_NONMATCHING"_s, QObject::tr(
"Discard records which could not be joined" ),
false ) );
74 auto nonMatchingSink = std::make_unique<QgsProcessingParameterFeatureSink>(
79 addParameter( nonMatchingSink.release() );
81 addOutput(
new QgsProcessingOutputNumber( u
"JOINED_COUNT"_s, QObject::tr(
"Number of joined features from input table" ) ) );
82 addOutput(
new QgsProcessingOutputNumber( u
"UNJOINABLE_COUNT"_s, QObject::tr(
"Number of unjoinable features from input table" ) ) );
85QString QgsJoinByNearestAlgorithm::shortHelpString()
const
87 return QObject::tr(
"This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the "
88 "input one, with additional attributes in its attribute table.\n\n"
89 "The additional attributes and their values are taken from a second vector layer, where features are joined "
90 "by finding the closest features from each layer. By default only the single nearest feature is joined,"
91 "but optionally the join can use the n-nearest neighboring features instead. If multiple features are found "
92 "with identical distances these will all be returned (even if the total number of features exceeds the specified "
93 "maximum feature count).\n\n"
94 "If a maximum distance is specified, then only features which are closer than this distance "
95 "will be matched.\n\n"
96 "The output features will contain the selected attributes from the nearest feature, "
97 "along with new attributes for the distance to the near feature, the index of the feature, "
98 "and the coordinates of the closest point on the input feature (feature_x, feature_y) "
99 "to the matched nearest feature, and the coordinates of the closet point on the matched feature "
100 "(nearest_x, nearest_y).\n\n"
101 "This algorithm uses purely Cartesian calculations for distance, and does not consider "
102 "geodetic or ellipsoid properties when determining feature proximity." );
105QString QgsJoinByNearestAlgorithm::shortDescription()
const
107 return QObject::tr(
"Joins a layer to another layer, using the closest features (nearest neighbors)." );
115QgsJoinByNearestAlgorithm *QgsJoinByNearestAlgorithm::createInstance()
const
117 return new QgsJoinByNearestAlgorithm();
122 const int neighbors = parameterAsInt( parameters, u
"NEIGHBORS"_s, context );
123 const bool discardNonMatching = parameterAsBoolean( parameters, u
"DISCARD_NONMATCHING"_s, context );
124 const double maxDistance = parameters.value( u
"MAX_DISTANCE"_s ).isValid() ? parameterAsDouble( parameters, u
"MAX_DISTANCE"_s, context ) : std::numeric_limits<double>::quiet_NaN();
125 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u
"INPUT"_s, context ) );
129 std::unique_ptr<QgsProcessingFeatureSource> input2( parameterAsSource( parameters, u
"INPUT_2"_s, context ) );
133 const bool sameSourceAndTarget = parameters.value( u
"INPUT"_s ) == parameters.value( u
"INPUT_2"_s );
135 const QString prefix = parameterAsString( parameters, u
"PREFIX"_s, context );
136 const QStringList fieldsToCopy = parameterAsStrings( parameters, u
"FIELDS_TO_COPY"_s, context );
140 if ( fieldsToCopy.empty() )
142 outFields2 = input2->fields();
143 fields2Indices.reserve( outFields2.
count() );
144 for (
int i = 0; i < outFields2.
count(); ++i )
151 fields2Indices.reserve( fieldsToCopy.count() );
152 for (
const QString &field : fieldsToCopy )
154 const int index = input2->fields().lookupField( field );
157 fields2Indices << index;
158 outFields2.
append( input2->fields().at( index ) );
163 if ( !prefix.isEmpty() )
165 for (
int i = 0; i < outFields2.
count(); ++i )
167 outFields2.
rename( i, prefix + outFields2[i].name() );
177 resultFields.
append(
QgsField( u
"distance"_s, QMetaType::Type::Double ) );
178 resultFields.
append(
QgsField( u
"feature_x"_s, QMetaType::Type::Double ) );
179 resultFields.
append(
QgsField( u
"feature_y"_s, QMetaType::Type::Double ) );
180 resultFields.
append(
QgsField( u
"nearest_x"_s, QMetaType::Type::Double ) );
181 resultFields.
append(
QgsField( u
"nearest_y"_s, QMetaType::Type::Double ) );
185 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u
"OUTPUT"_s, context, dest, outFields, input->wkbType(), input->sourceCrs(),
QgsFeatureSink::RegeneratePrimaryKey ) );
186 if ( parameters.value( u
"OUTPUT"_s ).isValid() && !sink )
189 QString destNonMatching1;
190 std::unique_ptr<QgsFeatureSink> sinkNonMatching1( parameterAsSink( parameters, u
"NON_MATCHING"_s, context, destNonMatching1, input->fields(), input->wkbType(), input->sourceCrs(),
QgsFeatureSink::RegeneratePrimaryKey ) );
191 if ( parameters.value( u
"NON_MATCHING"_s ).isValid() && !sinkNonMatching1 )
196 QHash<QgsFeatureId, QgsAttributes> input2AttributeCache;
197 double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1;
211 for (
int field2Index : fields2Indices )
213 attributes << f.
attribute( field2Index );
215 input2AttributeCache.insert( f.
id(), attributes );
223 nullMatch.reserve( fields2Indices.size() + 6 );
224 for (
int i = 0; i < fields2Indices.count() + 6; ++i )
225 nullMatch << QVariant();
227 long long joinedCount = 0;
228 long long unjoinedCount = 0;
231 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
244 if ( !f.hasGeometry() )
247 if ( sinkNonMatching1 )
250 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, u
"NON_MATCHING"_s ) );
252 if ( sink && !discardNonMatching )
255 attr.append( nullMatch );
256 f.setAttributes( attr );
267 const double searchDistance = std::isnan( maxDistance ) ? 0 : std::max( std::numeric_limits<double>::min(), maxDistance );
268 const QList<QgsFeatureId> nearest = index.nearestNeighbor( f.geometry(), neighbors + ( sameSourceAndTarget ? 1 : 0 ), searchDistance );
270 if ( nearest.count() > neighbors + ( sameSourceAndTarget ? 1 : 0 ) )
272 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 ) );
279 if ( sameSourceAndTarget &&
id == f.id() )
285 attr.append( input2AttributeCache.value(
id ) );
291 attr.append( line->length() );
292 attr.append( line->startPoint().x() );
293 attr.append( line->startPoint().y() );
294 attr.append( line->endPoint().x() );
295 attr.append( line->endPoint().y() );
299 attr.append( QVariant() );
300 attr.append( QVariant() );
301 attr.append( QVariant() );
302 attr.append( QVariant() );
303 attr.append( QVariant() );
314 if ( sinkNonMatching1 )
317 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, u
"NON_MATCHING"_s ) );
319 if ( !discardNonMatching && sink )
322 attr.append( nullMatch );
323 f.setAttributes( attr );
333 outputs.insert( u
"JOINED_COUNT"_s, joinedCount );
334 outputs.insert( u
"UNJOINABLE_COUNT"_s, unjoinedCount );
338 outputs.insert( u
"OUTPUT"_s, dest );
340 if ( sinkNonMatching1 )
342 sinkNonMatching1->finalize();
343 outputs.insert( u
"NON_MATCHING"_s, 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