26 QString QgsJoinByNearestAlgorithm::name()
const
28 return QStringLiteral(
"joinbynearest" );
31 QString QgsJoinByNearestAlgorithm::displayName()
const
33 return QObject::tr(
"Join attributes by nearest" );
36 QStringList QgsJoinByNearestAlgorithm::tags()
const
38 return QObject::tr(
"join,connect,attributes,values,fields,tables,proximity,closest,neighbour,neighbor,n-nearest,distance" ).split(
',' );
41 QString QgsJoinByNearestAlgorithm::group()
const
43 return QObject::tr(
"Vector general" );
46 QString QgsJoinByNearestAlgorithm::groupId()
const
48 return QStringLiteral(
"vectorgeneral" );
51 void QgsJoinByNearestAlgorithm::initAlgorithm(
const QVariantMap & )
54 QObject::tr(
"Input layer" ) ) );
56 QObject::tr(
"Input layer 2" ) ) );
59 QObject::tr(
"Layer 2 fields to copy (leave empty to copy all fields)" ),
64 QObject::tr(
"Discard records which could not be joined" ),
68 QObject::tr(
"Joined field prefix" ), QVariant(),
false,
true ) );
74 QObject::tr(
"Maximum distance" ), QVariant(), QStringLiteral(
"INPUT" ),
true, 0 ) );
78 std::unique_ptr< QgsProcessingParameterFeatureSink > nonMatchingSink = std::make_unique< QgsProcessingParameterFeatureSink >(
82 addParameter( nonMatchingSink.release() );
84 addOutput(
new QgsProcessingOutputNumber( QStringLiteral(
"JOINED_COUNT" ), QObject::tr(
"Number of joined features from input table" ) ) );
85 addOutput(
new QgsProcessingOutputNumber( QStringLiteral(
"UNJOINABLE_COUNT" ), QObject::tr(
"Number of unjoinable features from input table" ) ) );
88 QString QgsJoinByNearestAlgorithm::shortHelpString()
const
90 return QObject::tr(
"This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the "
91 "input one, with additional attributes in its attribute table.\n\n"
92 "The additional attributes and their values are taken from a second vector layer, where features are joined "
93 "by finding the closest features from each layer. By default only the single nearest feature is joined,"
94 "but optionally the join can use the n-nearest neighboring features instead. If multiple features are found "
95 "with identical distances these will all be returned (even if the total number of features exceeds the specified "
96 "maximum feature count).\n\n"
97 "If a maximum distance is specified, then only features which are closer than this distance "
98 "will be matched.\n\n"
99 "The output features will contain the selected attributes from the nearest feature, "
100 "along with new attributes for the distance to the near feature, the index of the feature, "
101 "and the coordinates of the closest point on the input feature (feature_x, feature_y) "
102 "to the matched nearest feature, and the coordinates of the closet point on the matched feature "
103 "(nearest_x, nearest_y).\n\n"
104 "This algorithm uses purely Cartesian calculations for distance, and does not consider "
105 "geodetic or ellipsoid properties when determining feature proximity." );
108 QString QgsJoinByNearestAlgorithm::shortDescription()
const
110 return QObject::tr(
"Joins a layer to another layer, using the closest features (nearest neighbors)." );
113 QgsJoinByNearestAlgorithm *QgsJoinByNearestAlgorithm::createInstance()
const
115 return new QgsJoinByNearestAlgorithm();
120 const int neighbors = parameterAsInt( parameters, QStringLiteral(
"NEIGHBORS" ), context );
121 const bool discardNonMatching = parameterAsBoolean( parameters, QStringLiteral(
"DISCARD_NONMATCHING" ), context );
122 const double maxDistance = parameters.value( QStringLiteral(
"MAX_DISTANCE" ) ).isValid() ? parameterAsDouble( parameters, QStringLiteral(
"MAX_DISTANCE" ), context ) : std::numeric_limits< double >::quiet_NaN();
123 std::unique_ptr< QgsProcessingFeatureSource > input( parameterAsSource( parameters, QStringLiteral(
"INPUT" ), context ) );
127 std::unique_ptr< QgsProcessingFeatureSource > input2( parameterAsSource( parameters, QStringLiteral(
"INPUT_2" ), context ) );
131 const bool sameSourceAndTarget = parameters.value( QStringLiteral(
"INPUT" ) ) == parameters.value( QStringLiteral(
"INPUT_2" ) );
133 const QString prefix = parameterAsString( parameters, QStringLiteral(
"PREFIX" ), context );
134 const QStringList fieldsToCopy = parameterAsFields( parameters, QStringLiteral(
"FIELDS_TO_COPY" ), context );
138 if ( fieldsToCopy.empty() )
140 outFields2 = input2->fields();
141 fields2Indices.reserve( outFields2.
count() );
142 for (
int i = 0; i < outFields2.
count(); ++i )
149 fields2Indices.reserve( fieldsToCopy.count() );
150 for (
const QString &
field : fieldsToCopy )
155 fields2Indices << index;
156 outFields2.
append( input2->fields().at( index ) );
161 if ( !prefix.isEmpty() )
163 for (
int i = 0; i < outFields2.
count(); ++i )
165 outFields2.
rename( i, prefix + outFields2[ i ].name() );
174 resultFields.
append(
QgsField( QStringLiteral(
"n" ), QVariant::Int ) );
175 resultFields.
append(
QgsField( QStringLiteral(
"distance" ), QVariant::Double ) );
176 resultFields.
append(
QgsField( QStringLiteral(
"feature_x" ), QVariant::Double ) );
177 resultFields.
append(
QgsField( QStringLiteral(
"feature_y" ), QVariant::Double ) );
178 resultFields.
append(
QgsField( QStringLiteral(
"nearest_x" ), QVariant::Double ) );
179 resultFields.
append(
QgsField( QStringLiteral(
"nearest_y" ), QVariant::Double ) );
183 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT" ), context, dest, outFields,
185 if ( parameters.value( QStringLiteral(
"OUTPUT" ) ).isValid() && !sink )
188 QString destNonMatching1;
189 std::unique_ptr< QgsFeatureSink > sinkNonMatching1( parameterAsSink( parameters, QStringLiteral(
"NON_MATCHING" ), context, destNonMatching1, input->fields(),
191 if ( parameters.value( QStringLiteral(
"NON_MATCHING" ) ).isValid() && !sinkNonMatching1 )
196 QHash< QgsFeatureId, QgsAttributes > input2AttributeCache;
197 double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1;
212 for (
int j = 0; j < f.
attributes().count(); ++j )
214 if ( ! fields2Indices.contains( j ) )
218 input2AttributeCache.insert( f.
id(), attributes );
227 nullMatch.reserve( fields2Indices.size() + 6 );
228 for (
int i = 0; i < fields2Indices.count() + 6; ++i )
229 nullMatch << QVariant();
231 long long joinedCount = 0;
232 long long unjoinedCount = 0;
235 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
248 if ( !f.hasGeometry() )
251 if ( sinkNonMatching1 )
254 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral(
"NON_MATCHING" ) ) );
256 if ( sink && !discardNonMatching )
259 attr.append( nullMatch );
260 f.setAttributes( attr );
271 const double searchDistance = std::isnan( maxDistance ) ? 0 : std::max( std::numeric_limits<double>::min(), maxDistance );
272 const QList< QgsFeatureId > nearest = index.nearestNeighbor( f.geometry(), neighbors + ( sameSourceAndTarget ? 1 : 0 ), searchDistance );
274 if ( nearest.count() > neighbors + ( sameSourceAndTarget ? 1 : 0 ) )
276 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 ) );
283 if ( sameSourceAndTarget &&
id == f.id() )
289 attr.append( input2AttributeCache.value(
id ) );
293 if (
const QgsLineString *line = qgsgeometry_cast< const QgsLineString *>( closestLine.
constGet() ) )
295 attr.append( line->length() );
296 attr.append( line->startPoint().x() );
297 attr.append( line->startPoint().y() );
298 attr.append( line->endPoint().x() );
299 attr.append( line->endPoint().y() );
303 attr.append( QVariant() );
304 attr.append( QVariant() );
305 attr.append( QVariant() );
306 attr.append( QVariant() );
307 attr.append( QVariant() );
318 if ( sinkNonMatching1 )
321 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral(
"NON_MATCHING" ) ) );
323 if ( !discardNonMatching && sink )
326 attr.append( nullMatch );
327 f.setAttributes( attr );
337 outputs.insert( QStringLiteral(
"JOINED_COUNT" ), joinedCount );
338 outputs.insert( QStringLiteral(
"UNJOINABLE_COUNT" ), unjoinedCount );
340 outputs.insert( QStringLiteral(
"OUTPUT" ), dest );
341 if ( sinkNonMatching1 )
342 outputs.insert( QStringLiteral(
"NON_MATCHING" ), destNonMatching1 );