25QString QgsHubDistanceAlgorithm::name()
const
27 return QStringLiteral(
"distancetonearesthub" );
30QString QgsHubDistanceAlgorithm::displayName()
const
32 return QObject::tr(
"Distance to nearest hub" );
35QStringList QgsHubDistanceAlgorithm::tags()
const
37 return QObject::tr(
"lines,points,hub,spoke,distance" ).split(
',' );
40QString QgsHubDistanceAlgorithm::group()
const
42 return QObject::tr(
"Vector analysis" );
45QString QgsHubDistanceAlgorithm::groupId()
const
47 return QStringLiteral(
"vectoranalysis" );
50QString QgsHubDistanceAlgorithm::shortHelpString()
const
52 return QObject::tr(
"This algorithm computes the distance between features from the source layer to the closest feature "
53 "from the destination layer.\n\n"
54 "Distance calculations are based on the feature's bounding box center.\n\n"
55 "The resulting line layer contains lines linking each origin point with its nearest destination feature.\n\n"
56 "The resulting point layer contains each origin feature's center point with additional fields indicating the identifier "
57 "of the nearest destination feature and the distance to it."
61QString QgsHubDistanceAlgorithm::shortDescription()
const
63 return QObject::tr(
"Computes the distance between features from the source layer to the closest feature from the destination layer." );
71QgsHubDistanceAlgorithm *QgsHubDistanceAlgorithm::createInstance()
const
73 return new QgsHubDistanceAlgorithm();
76void QgsHubDistanceAlgorithm::initAlgorithm(
const QVariantMap & )
80 addParameter(
new QgsProcessingParameterField( QStringLiteral(
"FIELD" ), QObject::tr(
"Hub layer name attribute" ), QVariant(), QStringLiteral(
"HUBS" ) ) );
82 const QStringList options = QStringList()
83 << QObject::tr(
"Meters" )
84 << QObject::tr(
"Feet" )
85 << QObject::tr(
"Miles" )
86 << QObject::tr(
"Kilometers" )
87 << QObject::tr(
"Layer Units" );
88 addParameter(
new QgsProcessingParameterEnum( QStringLiteral(
"UNIT" ), QObject::tr(
"Measurement unit" ), options,
false, 0 ) );
95 if ( parameters.value( QStringLiteral(
"INPUT" ) ) == parameters.value( QStringLiteral(
"HUBS" ) ) )
96 throw QgsProcessingException( QObject::tr(
"The same layer was specified for both the hubs and spokes. The hubs and spoke layers must be different layers." ) );
98 std::unique_ptr<QgsProcessingFeatureSource> hubSource( parameterAsSource( parameters, QStringLiteral(
"HUBS" ), context ) );
102 std::unique_ptr<QgsProcessingFeatureSource> spokeSource( parameterAsSource( parameters, QStringLiteral(
"INPUT" ), context ) );
106 const QString fieldHubName = parameterAsString( parameters, QStringLiteral(
"FIELD" ), context );
107 const int hubNameIndex = hubSource->fields().lookupField( fieldHubName );
109 const int unitIndex = parameterAsEnum( parameters, QStringLiteral(
"UNIT" ), context );
128 fields.
append(
QgsField( QStringLiteral(
"HubName" ), QMetaType::Type::QString ) );
129 fields.
append(
QgsField( QStringLiteral(
"HubDist" ), QMetaType::Type::Double ) );
133 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT_LINES" ), context, linesDest, fields,
Qgis::WkbType::LineString, hubSource->sourceCrs() ) );
138 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT_POINTS" ), context, pointsDest, fields,
Qgis::WkbType::Point, hubSource->sourceCrs() ) );
145 QHash<QgsFeatureId, QVariant> hubsAttributeCache;
146 double step = hubSource->featureCount() > 0 ? 50.0 / hubSource->featureCount() : 1;
149 if ( feedback-> isCanceled() )
154 hubsAttributeCache.insert( f.
id(), f.
attributes().at( hubNameIndex ) );
167 step = spokeSource->featureCount() > 0 ? 50.0 / spokeSource->featureCount() : 1;
184 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, QStringLiteral(
"OUTPUT_LINES" ) ) );
188 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral(
"OUTPUT_POINTS" ) ) );
195 const QList<QgsFeatureId> neighbors = hubsIndex.nearestNeighbor( point, 1 );
196 if ( neighbors.isEmpty() )
198 feedback->
pushWarning( QObject::tr(
"Feature %1 does not have any neighbour hubs." ) );
202 const QgsPointXY hub = hubsIndex.geometry( neighbors.at( 0 ) ).boundingBox().center();
211 attrs << hubsAttributeCache.value( neighbors.at( 0 ) ) << hubDistance;
220 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, QStringLiteral(
"OUTPUT_LINES" ) ) );
229 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral(
"OUTPUT_POINTS" ) ) );
236 linesSink->finalize();
240 pointsSink->finalize();
246 results.insert( QStringLiteral(
"OUTPUT_LINES" ), linesDest );
250 results.insert( QStringLiteral(
"OUTPUT_POINTS" ), pointsDest );
@ VectorAnyGeometry
Any vector layer with geometry.
@ VectorPoint
Vector point layers.
@ VectorLine
Vector line layers.
DistanceUnit
Units of distance.
@ Miles
Terrestrial miles.
@ Unknown
Unknown distance unit.
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
double convertLengthMeasurement(double length, Qgis::DistanceUnit toUnits) const
Takes a length measurement calculated by this QgsDistanceArea object and converts it to a different d...
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
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).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
@ 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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
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.
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.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
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 vector layer or feature source field 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,...
QList< int > QgsAttributeList
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.