QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsalgorithmlineintersection.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmlineintersection.cpp
3 ---------------------
4 begin : April 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson 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
19
20#include "qgsgeometryengine.h"
21#include "qgsspatialindex.h"
22
24
25QString QgsLineIntersectionAlgorithm::name() const
26{
27 return QStringLiteral( "lineintersections" );
28}
29
30QString QgsLineIntersectionAlgorithm::displayName() const
31{
32 return QObject::tr( "Line intersections" );
33}
34
35QStringList QgsLineIntersectionAlgorithm::tags() const
36{
37 return QObject::tr( "line,intersection" ).split( ',' );
38}
39
40QString QgsLineIntersectionAlgorithm::group() const
41{
42 return QObject::tr( "Vector overlay" );
43}
44
45QString QgsLineIntersectionAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectoroverlay" );
48}
49
50void QgsLineIntersectionAlgorithm::initAlgorithm( const QVariantMap & )
51{
52 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
53 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INTERSECT" ), QObject::tr( "Intersect layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
54
55 addParameter( new QgsProcessingParameterField(
56 QStringLiteral( "INPUT_FIELDS" ),
57 QObject::tr( "Input fields to keep (leave empty to keep all fields)" ), QVariant(),
58 QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Any,
59 true, true
60 ) );
61 addParameter( new QgsProcessingParameterField(
62 QStringLiteral( "INTERSECT_FIELDS" ),
63 QObject::tr( "Intersect fields to keep (leave empty to keep all fields)" ), QVariant(),
64 QStringLiteral( "INTERSECT" ), Qgis::ProcessingFieldParameterDataType::Any,
65 true, true
66 ) );
67
68 auto prefix = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "INTERSECT_FIELDS_PREFIX" ), QObject::tr( "Intersect fields prefix" ), QString(), false, true );
69 prefix->setFlags( prefix->flags() | Qgis::ProcessingParameterFlag::Advanced );
70 addParameter( prefix.release() );
71
72 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Intersections" ), Qgis::ProcessingSourceType::VectorPoint ) );
73}
74
75QString QgsLineIntersectionAlgorithm::shortHelpString() const
76{
77 return QObject::tr( "This algorithm creates point features where the lines in the Intersect layer intersect the lines in the Input layer." );
78}
79
80QString QgsLineIntersectionAlgorithm::shortDescription() const
81{
82 return QObject::tr( "Creates point features at the intersection of lines from two different layers." );
83}
84
85Qgis::ProcessingAlgorithmDocumentationFlags QgsLineIntersectionAlgorithm::documentationFlags() const
86{
88}
89
90QgsLineIntersectionAlgorithm *QgsLineIntersectionAlgorithm::createInstance() const
91{
92 return new QgsLineIntersectionAlgorithm();
93}
94
95QVariantMap QgsLineIntersectionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
96{
97 std::unique_ptr<QgsFeatureSource> sourceA( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
98 if ( !sourceA )
99 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
100
101 std::unique_ptr<QgsFeatureSource> sourceB( parameterAsSource( parameters, QStringLiteral( "INTERSECT" ), context ) );
102 if ( !sourceB )
103 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INTERSECT" ) ) );
104
105 const QStringList fieldsA = parameterAsStrings( parameters, QStringLiteral( "INPUT_FIELDS" ), context );
106 const QStringList fieldsB = parameterAsStrings( parameters, QStringLiteral( "INTERSECT_FIELDS" ), context );
107
108 QgsAttributeList fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( fieldsA, sourceA->fields() );
109 QgsAttributeList fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( fieldsB, sourceB->fields() );
110
111 QString intersectFieldsPrefix = parameterAsString( parameters, QStringLiteral( "INTERSECT_FIELDS_PREFIX" ), context );
113 QgsProcessingUtils::indicesToFields( fieldIndicesA, sourceA->fields() ),
114 QgsProcessingUtils::indicesToFields( fieldIndicesB, sourceB->fields() ),
115 intersectFieldsPrefix
116 );
117
118 QString dest;
119 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, Qgis::WkbType::Point, sourceA->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
120 if ( !sink )
121 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
122
123 QgsSpatialIndex spatialIndex( sourceB->getFeatures( QgsFeatureRequest().setNoAttributes().setDestinationCrs( sourceA->sourceCrs(), context.transformContext() ) ), feedback );
124 QgsFeature outFeature;
125 QgsFeatureIterator features = sourceA->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( fieldIndicesA ) );
126 double step = sourceA->featureCount() > 0 ? 100.0 / sourceA->featureCount() : 1;
127 int i = 0;
128 QgsFeature inFeatureA;
129 while ( features.nextFeature( inFeatureA ) )
130 {
131 i++;
132 if ( feedback->isCanceled() )
133 {
134 break;
135 }
136
137 if ( !inFeatureA.hasGeometry() )
138 continue;
139
140 QgsGeometry inGeom = inFeatureA.geometry();
141 QgsFeatureIds lines = qgis::listToSet( spatialIndex.intersects( inGeom.boundingBox() ) );
142 if ( !lines.empty() )
143 {
144 // use prepared geometries for faster intersection tests
145 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( inGeom.constGet() ) );
146 engine->prepareGeometry();
147
149 request.setDestinationCrs( sourceA->sourceCrs(), context.transformContext() );
150 request.setSubsetOfAttributes( fieldIndicesB );
151
152 QgsFeature inFeatureB;
153 QgsFeatureIterator featuresB = sourceB->getFeatures( request );
154 while ( featuresB.nextFeature( inFeatureB ) )
155 {
156 if ( feedback->isCanceled() )
157 {
158 break;
159 }
160
161 QgsGeometry tmpGeom = inFeatureB.geometry();
162 if ( engine->intersects( tmpGeom.constGet() ) )
163 {
164 QgsMultiPointXY points;
165 QgsGeometry intersectGeom = inGeom.intersection( tmpGeom );
166 QgsAttributes outAttributes;
167 for ( int a : std::as_const( fieldIndicesA ) )
168 {
169 outAttributes.append( inFeatureA.attribute( a ) );
170 }
171 for ( int b : std::as_const( fieldIndicesB ) )
172 {
173 outAttributes.append( inFeatureB.attribute( b ) );
174 }
176 {
177 const QVector<QgsGeometry> geomCollection = intersectGeom.asGeometryCollection();
178 for ( const QgsGeometry &part : geomCollection )
179 {
180 if ( part.type() == Qgis::GeometryType::Point )
181 {
182 if ( part.isMultipart() )
183 {
184 points = part.asMultiPoint();
185 }
186 else
187 {
188 points.append( part.asPoint() );
189 }
190 }
191 }
192 }
193 else if ( intersectGeom.type() == Qgis::GeometryType::Point )
194 {
195 if ( intersectGeom.isMultipart() )
196 {
197 points = intersectGeom.asMultiPoint();
198 }
199 else
200 {
201 points.append( intersectGeom.asPoint() );
202 }
203 }
204 for ( const QgsPointXY &j : std::as_const( points ) )
205 {
206 outFeature.setGeometry( QgsGeometry::fromPointXY( j ) );
207 outFeature.setAttributes( outAttributes );
208 if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
209 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
210 }
211 }
212 }
213 }
214
215 feedback->setProgress( i * step );
216 }
217
218 sink->finalize();
219
220 QVariantMap outputs;
221 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
222 return outputs;
223}
224
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
@ VectorLine
Vector line layers.
Definition qgis.h:3535
@ Point
Points.
Definition qgis.h:359
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3619
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
@ Point
Point.
Definition qgis.h:279
@ GeometryCollection
GeometryCollection.
Definition qgis.h:286
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
A vector of attributes.
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 & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
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...
@ 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...
Definition qgsfeature.h:58
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
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
Container of fields for a vector layer.
Definition qgsfields.h:46
A geometry is the spatial representation of a feature.
QgsMultiPointXY asMultiPoint() const
Returns the contents of the geometry as a multi-point.
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
Qgis::GeometryType type
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points shared by this geometry and other.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.).
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Represents a 2D point.
Definition qgspointxy.h:60
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 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 indicesToFields(const QList< int > &indices, const QgsFields &fields)
Returns a subset of fields based on the indices of desired fields.
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
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.
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
QSet< QgsFeatureId > QgsFeatureIds
QList< int > QgsAttributeList
Definition qgsfield.h:28
QVector< QgsPointXY > QgsMultiPointXY
A collection of QgsPoints that share a common collection of attributes.
Definition qgsgeometry.h:96