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