QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmshortestline.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmshortestline.cpp
3 ---------------------
4 begin : September 2021
5 copyright : (C) 2020 by Matteo Ghetta, Clemens Raffler
6 email : clemens dot raffler 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
18//Disclaimer:This feature was originally developed in Python by: Matteo Ghetta, August 2021
19
21#include "qgsdistancearea.h"
22#include "qgsspatialindex.h"
23
25
26QString QgsShortestLineAlgorithm::name() const
27{
28 return QStringLiteral( "shortestline" );
29}
30
31QString QgsShortestLineAlgorithm::displayName() const
32{
33 return QObject::tr( "Shortest line between features" );
34}
35
36QStringList QgsShortestLineAlgorithm::tags() const
37{
38 return QObject::tr( "distance,shortest,minimum,nearest,closest,proximity" ).split( ',' );
39}
40
41QString QgsShortestLineAlgorithm::group() const
42{
43 return QObject::tr( "Vector analysis" );
44}
45
46QString QgsShortestLineAlgorithm::groupId() const
47{
48 return QStringLiteral( "vectoranalysis" );
49}
50
51QString QgsShortestLineAlgorithm::shortDescription() const
52{
53 return QObject::tr( "Calculates the shortest lines between features in source and destination layers." );
54}
55
56QString QgsShortestLineAlgorithm::shortHelpString() const
57{
58 return QObject::tr( "This algorithm creates a line layer as the "
59 "shortest line between the source and the destination layer. "
60 "By default only the first nearest feature of the "
61 "destination layer is taken into account. "
62 "The n-nearest neighboring features number can be specified.\n\n"
63 "If a maximum distance is specified, then only "
64 "features which are closer than this distance will "
65 "be considered.\n\nThe output features will contain all the "
66 "source layer attributes, all the attributes from the n-nearest "
67 "feature and the additional field of the distance.\n\n"
68 "This algorithm uses purely Cartesian calculations for distance, "
69 "and does not consider geodetic or ellipsoid properties when "
70 "determining feature proximity. The measurement and output coordinate "
71 "system is based on the coordinate system of the source layer."
72 );
73}
74
75QgsShortestLineAlgorithm *QgsShortestLineAlgorithm::createInstance() const
76{
77 return new QgsShortestLineAlgorithm();
78}
79
80void QgsShortestLineAlgorithm::initAlgorithm( const QVariantMap & )
81{
82 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "SOURCE" ), QObject::tr( "Source layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
83 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "DESTINATION" ), QObject::tr( "Destination layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
84 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Method" ), QStringList() << "Distance to Nearest Point on feature" << "Distance to Feature Centroid", false, 0 ) );
85 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "NEIGHBORS" ), QObject::tr( "Maximum number of neighbors" ), Qgis::ProcessingNumberParameterType::Integer, 1, false, 1 ) );
86 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "DISTANCE" ), QObject::tr( "Maximum distance" ), QVariant(), QString( "SOURCE" ), true ) );
87 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Shortest lines" ), Qgis::ProcessingSourceType::VectorLine ) );
88}
89
90bool QgsShortestLineAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
91{
92 mSource.reset( parameterAsSource( parameters, QStringLiteral( "SOURCE" ), context ) );
93 if ( !mSource )
94 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "SOURCE" ) ) );
95
96 mDestination.reset( parameterAsSource( parameters, QStringLiteral( "DESTINATION" ), context ) );
97 if ( !mDestination )
98 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "DESTINATION" ) ) );
99
100 mMethod = parameterAsInt( parameters, QStringLiteral( "METHOD" ), context );
101
102 mKNeighbors = parameterAsInt( parameters, QStringLiteral( "NEIGHBORS" ), context );
103
104 mMaxDistance = parameterAsDouble( parameters, QStringLiteral( "DISTANCE" ), context ); //defaults to zero if not set
105
106 return true;
107}
108
109QVariantMap QgsShortestLineAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
110{
111 if ( mKNeighbors > mDestination->featureCount() )
112 mKNeighbors = mDestination->featureCount();
113
114 QgsFields fields = QgsProcessingUtils::combineFields( mSource->fields(), mDestination->fields() );
115
116 QgsFields newFields;
117 newFields.append( QgsField( QStringLiteral( "distance" ), QMetaType::Type::Double ) );
118 fields = QgsProcessingUtils::combineFields( fields, newFields );
119
120 QString dest;
121 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::MultiLineString, mSource->sourceCrs() ) );
122 if ( !sink )
123 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
124
125 const QgsFeatureIterator destinationIterator = mDestination->getFeatures( QgsFeatureRequest().setDestinationCrs( mSource->sourceCrs(), context.transformContext() ) );
126 QHash<QgsFeatureId, QgsAttributes> destinationAttributeCache;
127 double step = mDestination->featureCount() > 0 ? 50.0 / mDestination->featureCount() : 1;
128 int i = 0;
129 const QgsSpatialIndex idx( destinationIterator, [&]( const QgsFeature &f ) -> bool {
130 i++;
131 if ( feedback-> isCanceled() )
132 return false;
133
134 feedback->setProgress( i * step );
135
136 destinationAttributeCache.insert( f.id(), f.attributes() );
137
139
140 step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
141 QgsFeatureIterator sourceIterator = mSource->getFeatures();
142
144 da.setSourceCrs( mSource->sourceCrs(), context.transformContext() );
145
146 QgsFeature sourceFeature;
147 while ( sourceIterator.nextFeature( sourceFeature ) )
148 {
149 if ( feedback->isCanceled() )
150 break;
151
152 const QgsGeometry sourceGeom = sourceFeature.geometry();
153 QgsFeatureIds nearestIds = qgis::listToSet( idx.nearestNeighbor( sourceGeom, mKNeighbors, mMaxDistance ) );
154
155 for ( const QgsFeatureId id : nearestIds )
156 {
157 QgsGeometry destinationGeom = idx.geometry( id );
158 if ( mMethod == 1 )
159 {
160 destinationGeom = idx.geometry( id ).centroid();
161 }
162
163 const QgsGeometry shortestLine = sourceGeom.shortestLine( destinationGeom );
164 double dist = 0;
165 try
166 {
167 dist = da.measureLength( shortestLine );
168 }
169 catch ( QgsCsException & )
170 {
171 throw QgsProcessingException( QObject::tr( "An error occurred while calculating shortest line length" ) );
172 }
173
174 QgsFeature f;
175 QgsAttributes attrs = sourceFeature.attributes();
176 attrs << destinationAttributeCache.value( id ) << dist;
177
178 f.setAttributes( attrs );
179 f.setGeometry( shortestLine );
180 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
181 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
182 }
183
184 i++;
185 feedback->setProgress( i * step );
186 }
187
188 sink->finalize();
189
190 QVariantMap outputs;
191 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
192 return outputs;
193}
194
@ VectorAnyGeometry
Any vector layer with geometry.
@ VectorLine
Vector line layers.
@ MultiLineString
MultiLineString.
A vector of attributes.
Custom exception class for Coordinate Reference System related exceptions.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
double measureLength(const QgsGeometry &geometry) const
Measures the length of a geometry.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
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...
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
QgsFeatureId id
Definition qgsfeature.h:66
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
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:53
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:70
A geometry is the spatial representation of a feature.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
QgsGeometry shortestLine(const QgsGeometry &other) const
Returns the shortest line joining this geometry to another geometry.
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.
A double numeric parameter for distance values.
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 numeric 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,...
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features