QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
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::shortHelpString() const
52{
53 return QObject::tr( "This algorithm creates a line layer as the "
54 "shortest line between the source and the destination layer. "
55 "By default only the first nearest feature of the "
56 "destination layer is taken into account. "
57 "The n-nearest neighboring features number can be specified.\n\n"
58 "If a maximum distance is specified, then only "
59 "features which are closer than this distance will "
60 "be considered.\n\nThe output features will contain all the "
61 "source layer attributes, all the attributes from the n-nearest "
62 "feature and the additional field of the distance.\n\n"
63 "This algorithm uses purely Cartesian calculations for distance, "
64 "and does not consider geodetic or ellipsoid properties when "
65 "determining feature proximity. The measurement and output coordinate "
66 "system is based on the coordinate system of the source layer."
67 );
68}
69
70QgsShortestLineAlgorithm *QgsShortestLineAlgorithm::createInstance() const
71{
72 return new QgsShortestLineAlgorithm();
73}
74
75void QgsShortestLineAlgorithm::initAlgorithm( const QVariantMap & )
76{
77 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "SOURCE" ), QObject::tr( "Source layer" ), QList<int>() << static_cast< int >( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
78 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "DESTINATION" ), QObject::tr( "Destination layer" ), QList<int>() << static_cast< int >( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
79 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Method" ), QStringList() << "Distance to Nearest Point on feature" << "Distance to Feature Centroid", false, 0 ) );
80 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "NEIGHBORS" ), QObject::tr( "Maximum number of neighbors" ), Qgis::ProcessingNumberParameterType::Integer, 1, false, 1 ) );
81 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "DISTANCE" ), QObject::tr( "Maximum distance" ), QVariant(), QString( "SOURCE" ), true ) );
82 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Shortest lines" ), Qgis::ProcessingSourceType::VectorLine ) );
83}
84
85bool QgsShortestLineAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
86{
87 mSource.reset( parameterAsSource( parameters, QStringLiteral( "SOURCE" ), context ) );
88 if ( !mSource )
89 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "SOURCE" ) ) );
90
91 mDestination.reset( parameterAsSource( parameters, QStringLiteral( "DESTINATION" ), context ) );
92 if ( !mDestination )
93 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "DESTINATION" ) ) );
94
95 mMethod = parameterAsInt( parameters, QStringLiteral( "METHOD" ), context );
96
97 mKNeighbors = parameterAsInt( parameters, QStringLiteral( "NEIGHBORS" ), context );
98
99 mMaxDistance = parameterAsDouble( parameters, QStringLiteral( "DISTANCE" ), context ); //defaults to zero if not set
100
101 return true;
102}
103
104QVariantMap QgsShortestLineAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
105{
106 if ( mKNeighbors > mDestination->featureCount() )
107 mKNeighbors = mDestination->featureCount();
108
109 QgsFields fields = QgsProcessingUtils::combineFields( mSource->fields(), mDestination->fields() );
110 fields.append( QgsField( QStringLiteral( "distance" ), QVariant::Double ) );
111
112 QString dest;
113 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::MultiLineString, mSource->sourceCrs() ) );
114 if ( !sink )
115 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
116
117 const QgsFeatureIterator destinationIterator = mDestination->getFeatures( QgsFeatureRequest().setDestinationCrs( mSource->sourceCrs(), context.transformContext() ) );
118 QHash< QgsFeatureId, QgsAttributes > destinationAttributeCache;
119 double step = mDestination->featureCount() > 0 ? 50.0 / mDestination->featureCount() : 1;
120 int i = 0;
121 const QgsSpatialIndex idx( destinationIterator, [&]( const QgsFeature & f )->bool
122 {
123 i++;
124 if ( feedback-> isCanceled() )
125 return false;
126
127 feedback->setProgress( i * step );
128
129 destinationAttributeCache.insert( f.id(), f.attributes() );
130
131 return true;
133
134 step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
135 QgsFeatureIterator sourceIterator = mSource->getFeatures();
136
138 da.setSourceCrs( mSource->sourceCrs(), context.transformContext() );
139
140 QgsFeature sourceFeature;
141 while ( sourceIterator.nextFeature( sourceFeature ) )
142 {
143 if ( feedback->isCanceled() )
144 break;
145
146 const QgsGeometry sourceGeom = sourceFeature.geometry();
147 QgsFeatureIds nearestIds = qgis::listToSet( idx.nearestNeighbor( sourceGeom, mKNeighbors, mMaxDistance ) );
148
149 for ( const QgsFeatureId id : nearestIds )
150 {
151 QgsGeometry destinationGeom = idx.geometry( id );
152 if ( mMethod == 1 )
153 {
154 destinationGeom = idx.geometry( id ).centroid();
155 }
156
157 const QgsGeometry shortestLine = sourceGeom.shortestLine( destinationGeom );
158 double dist = da.measureLength( shortestLine );
159 QgsFeature f;
160 QgsAttributes attrs = sourceFeature.attributes();
161 attrs << destinationAttributeCache.value( id ) << dist;
162
163 f.setAttributes( attrs );
164 f.setGeometry( shortestLine );
165 sink->addFeature( f, QgsFeatureSink::FastInsert );
166 }
167
168 i++;
169 feedback->setProgress( i * step );
170 }
171
172
173 QVariantMap outputs;
174 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
175 return outputs;
176}
177
@ VectorAnyGeometry
Any vector layer with geometry.
@ VectorLine
Vector line layers.
@ MultiLineString
MultiLineString.
A vector of attributes.
Definition: qgsattributes.h:59
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.
This class 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:56
QgsAttributes attributes
Definition: qgsfeature.h:65
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:160
QgsGeometry geometry
Definition: qgsfeature.h:67
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:167
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
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:45
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Appends a field. The field must have unique name, otherwise it is rejected (returns false)
Definition: qgsfields.cpp:59
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:162
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.
Definition: qgsexception.h:83
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
Definition: qgsfeatureid.h:37
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28