25using namespace Qt::StringLiterals;
29QString QgsShortestPathPointToLayerAlgorithm::name()
const
31 return u
"shortestpathpointtolayer"_s;
34QString QgsShortestPathPointToLayerAlgorithm::displayName()
const
36 return QObject::tr(
"Shortest path (point to layer)" );
39QStringList QgsShortestPathPointToLayerAlgorithm::tags()
const
41 return QObject::tr(
"network,path,shortest,fastest" ).split(
',' );
44QString QgsShortestPathPointToLayerAlgorithm::shortHelpString()
const
47 "This algorithm computes optimal (shortest or fastest) route between a given start point "
48 "and multiple end points defined by a point vector layer."
52QString QgsShortestPathPointToLayerAlgorithm::shortDescription()
const
55 "Computes optimal (shortest or fastest) route between a given start point "
56 "and multiple end points defined by a point vector layer."
65QgsShortestPathPointToLayerAlgorithm *QgsShortestPathPointToLayerAlgorithm::createInstance()
const
67 return new QgsShortestPathPointToLayerAlgorithm();
70void QgsShortestPathPointToLayerAlgorithm::initAlgorithm(
const QVariantMap & )
76 std::unique_ptr<QgsProcessingParameterNumber> maxEndPointDistanceFromNetwork
77 = std::make_unique<QgsProcessingParameterDistance>( u
"POINT_TOLERANCE"_s, QObject::tr(
"Maximum point distance from network" ), QVariant(), u
"INPUT"_s,
true, 0 );
79 maxEndPointDistanceFromNetwork->setHelp(
81 "Specifies an optional limit on the distance from the start and end points to the network layer.If the start point is further from the network than this distance an error will be raised. If "
82 "the end feature is further from the network than this distance it will be treated as non-routable."
85 addParameter( maxEndPointDistanceFromNetwork.release() );
89 auto outputNonRoutable = std::make_unique<QgsProcessingParameterFeatureSink>( u
"OUTPUT_NON_ROUTABLE"_s, QObject::tr(
"Non-routable features" ),
Qgis::ProcessingSourceType::VectorPoint, QVariant(),
true );
90 outputNonRoutable->setHelp( QObject::tr(
"An optional output which will be used to store any input features which could not be routed (e.g. those which are too far from the network layer)." ) );
91 outputNonRoutable->setCreateByDefault(
false );
92 addParameter( outputNonRoutable.release() );
97 loadCommonParams( parameters, context, feedback );
99 const QgsPointXY startPoint = parameterAsPoint( parameters, u
"START_POINT"_s, context, mNetwork->sourceCrs() );
101 std::unique_ptr<QgsFeatureSource> endPoints( parameterAsSource( parameters, u
"END_POINTS"_s, context ) );
106 newFields.
append(
QgsField( u
"start"_s, QMetaType::Type::QString ) );
107 newFields.
append(
QgsField( u
"end"_s, QMetaType::Type::QString ) );
108 newFields.
append(
QgsField( u
"cost"_s, QMetaType::Type::Double ) );
116 QString nonRoutableSinkId;
117 std::unique_ptr<QgsFeatureSink> nonRoutableSink( parameterAsSink( parameters, u
"OUTPUT_NON_ROUTABLE"_s, context, nonRoutableSinkId, endPoints->fields(),
Qgis::WkbType::Point, mNetwork->sourceCrs() ) );
119 const double pointDistanceThreshold = parameters.value( u
"POINT_TOLERANCE"_s ).isValid() ? parameterAsDouble( parameters, u
"POINT_TOLERANCE"_s, context ) : -1;
121 QVector<QgsPointXY> points;
122 points.push_front( startPoint );
123 QHash<int, QgsAttributes> sourceAttributes;
124 loadPoints( endPoints.get(), &points, &sourceAttributes, context, feedback,
nullptr );
126 feedback->
pushInfo( QObject::tr(
"Building graph…" ) );
127 QVector<QgsPointXY> snappedPoints;
128 mDirector->makeGraph( mBuilder.get(), points, snappedPoints, feedback );
130 const QgsPointXY snappedStartPoint = snappedPoints[0];
132 if ( pointDistanceThreshold >= 0 )
134 double distanceStartPointToNetwork = 0;
137 distanceStartPointToNetwork = mBuilder->distanceArea()->measureLine( startPoint, snappedStartPoint );
144 if ( distanceStartPointToNetwork > pointDistanceThreshold )
146 throw QgsProcessingException( QObject::tr(
"Start point is too far from the network layer (%1, maximum permitted is %2)" ).arg( distanceStartPointToNetwork ).arg( pointDistanceThreshold ) );
150 feedback->
pushInfo( QObject::tr(
"Calculating shortest paths…" ) );
151 std::unique_ptr<QgsGraph> graph( mBuilder->takeGraph() );
152 const int idxStart = graph->findVertex( snappedStartPoint );
156 QVector<double> costs;
159 QVector<QgsPointXY> route;
166 const double step = points.size() > 0 ? 100.0 / points.size() : 1;
167 for (
int i = 1; i < points.size(); i++ )
174 const QgsPointXY snappedPoint = snappedPoints.at( i );
175 const QgsPointXY originalPoint = points.at( i );
177 if ( pointDistanceThreshold >= 0 )
179 double distancePointToNetwork = 0;
182 distancePointToNetwork = mBuilder->distanceArea()->measureLine( originalPoint, snappedPoint );
189 if ( distancePointToNetwork > pointDistanceThreshold )
191 feedback->
pushWarning( QObject::tr(
"Point is too far from the network layer (%1, maximum permitted is %2)" ).arg( distancePointToNetwork ).arg( pointDistanceThreshold ) );
192 if ( nonRoutableSink )
195 attributes = sourceAttributes.value( i );
198 throw QgsProcessingException( writeFeatureError( nonRoutableSink.get(), parameters, u
"OUTPUT_NON_ROUTABLE"_s ) );
206 idxEnd = graph->findVertex( snappedPoint );
207 if ( tree.at( idxEnd ) == -1 )
209 feedback->
reportError( QObject::tr(
"There is no route from start point (%1) to end point (%2)." ).arg( startPoint.
toString(), originalPoint.
toString() ) );
211 attributes = sourceAttributes.value( i );
212 attributes.append( QVariant() );
213 attributes.append( originalPoint.
toString() );
221 route.push_front( graph->vertex( idxEnd ).point() );
222 cost = costs.at( idxEnd );
223 while ( idxEnd != idxStart )
225 idxEnd = graph->edge( tree.at( idxEnd ) ).fromVertex();
226 route.push_front( graph->vertex( idxEnd ).point() );
232 attributes = sourceAttributes.value( i );
233 attributes.append( startPoint.
toString() );
234 attributes.append( originalPoint.
toString() );
235 attributes.append( cost / mMultiplier );
247 outputs.insert( u
"OUTPUT"_s, dest );
248 if ( nonRoutableSink )
250 nonRoutableSink->finalize();
251 outputs.insert( u
"OUTPUT_NON_ROUTABLE"_s, nonRoutableSinkId );
@ VectorPoint
Vector point layers.
@ VectorLine
Vector line layers.
@ 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.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Custom exception class for Coordinate Reference System related exceptions.
@ 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.
void setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
void clearGeometry()
Removes any geometry associated with the feature.
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.
A geometry is the spatial representation of a feature.
static QgsGeometry fromPolylineXY(const QgsPolylineXY &polyline)
Creates a new LineString geometry from a list of QgsPointXY points.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
static void dijkstra(const QgsGraph *source, int startVertexIdx, int criterionNum, QVector< int > *resultTree=nullptr, QVector< double > *resultCost=nullptr)
Solve shortest path problem using Dijkstra algorithm.
QString toString(int precision=-1) const
Returns a string representation of the point (x, y) with a preset precision.
Contains information about the context in which a processing algorithm is executed.
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.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A point 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).