QGIS API Documentation 3.39.0-Master (3aed037ce22)
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#include "qgsgeometryengine.h"
20#include "qgsspatialindex.h"
21
23
24QString QgsLineIntersectionAlgorithm::name() const
25{
26 return QStringLiteral( "lineintersections" );
27}
28
29QString QgsLineIntersectionAlgorithm::displayName() const
30{
31 return QObject::tr( "Line intersections" );
32}
33
34QStringList QgsLineIntersectionAlgorithm::tags() const
35{
36 return QObject::tr( "line,intersection" ).split( ',' );
37}
38
39QString QgsLineIntersectionAlgorithm::group() const
40{
41 return QObject::tr( "Vector overlay" );
42}
43
44QString QgsLineIntersectionAlgorithm::groupId() const
45{
46 return QStringLiteral( "vectoroverlay" );
47}
48
49void QgsLineIntersectionAlgorithm::initAlgorithm( const QVariantMap & )
50{
51 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ),
52 QObject::tr( "Input layer" ), QList< int >() << static_cast< int >( Qgis::ProcessingSourceType::VectorLine ) ) );
53 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INTERSECT" ),
54 QObject::tr( "Intersect layer" ), QList< int >() << static_cast< int >( Qgis::ProcessingSourceType::VectorLine ) ) );
55
56 addParameter( new QgsProcessingParameterField(
57 QStringLiteral( "INPUT_FIELDS" ),
58 QObject::tr( "Input fields to keep (leave empty to keep all fields)" ), QVariant(),
59 QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Any,
60 true, true ) );
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 std::unique_ptr< QgsProcessingParameterString > prefix = std::make_unique< QgsProcessingParameterString >( QStringLiteral( "INTERSECT_FIELDS_PREFIX" ), QObject::tr( "Intersect fields prefix" ), QString(), false, true );
68 prefix->setFlags( prefix->flags() | Qgis::ProcessingParameterFlag::Advanced );
69 addParameter( prefix.release() );
70
71 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Intersections" ), Qgis::ProcessingSourceType::VectorPoint ) );
72}
73
74QString QgsLineIntersectionAlgorithm::shortHelpString() const
75{
76 return QObject::tr( "This algorithm creates point features where the lines in the Intersect layer intersect the lines in the Input layer." );
77}
78
79Qgis::ProcessingAlgorithmDocumentationFlags QgsLineIntersectionAlgorithm::documentationFlags() const
80{
82}
83
84QgsLineIntersectionAlgorithm *QgsLineIntersectionAlgorithm::createInstance() const
85{
86 return new QgsLineIntersectionAlgorithm();
87}
88
89QVariantMap QgsLineIntersectionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
90{
91 std::unique_ptr< QgsFeatureSource > sourceA( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
92 if ( !sourceA )
93 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
94
95 std::unique_ptr< QgsFeatureSource > sourceB( parameterAsSource( parameters, QStringLiteral( "INTERSECT" ), context ) );
96 if ( !sourceB )
97 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INTERSECT" ) ) );
98
99 const QStringList fieldsA = parameterAsStrings( parameters, QStringLiteral( "INPUT_FIELDS" ), context );
100 const QStringList fieldsB = parameterAsStrings( parameters, QStringLiteral( "INTERSECT_FIELDS" ), context );
101
102 QgsAttributeList fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( fieldsA, sourceA->fields() );
103 QgsAttributeList fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( fieldsB, sourceB->fields() );
104
105 QString intersectFieldsPrefix = parameterAsString( parameters, QStringLiteral( "INTERSECT_FIELDS_PREFIX" ), context );
107 QgsProcessingUtils::indicesToFields( fieldIndicesA, sourceA->fields() ),
108 QgsProcessingUtils::indicesToFields( fieldIndicesB, sourceB->fields() ),
109 intersectFieldsPrefix );
110
111 QString dest;
112 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, Qgis::WkbType::Point, sourceA->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
113 if ( !sink )
114 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
115
116 QgsSpatialIndex spatialIndex( sourceB->getFeatures( QgsFeatureRequest().setNoAttributes().setDestinationCrs( sourceA->sourceCrs(), context.transformContext() ) ), feedback );
117 QgsFeature outFeature;
118 QgsFeatureIterator features = sourceA->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( fieldIndicesA ) );
119 double step = sourceA->featureCount() > 0 ? 100.0 / sourceA->featureCount() : 1;
120 int i = 0;
121 QgsFeature inFeatureA;
122 while ( features.nextFeature( inFeatureA ) )
123 {
124 i++;
125 if ( feedback->isCanceled() )
126 {
127 break;
128 }
129
130 if ( !inFeatureA.hasGeometry() )
131 continue;
132
133 QgsGeometry inGeom = inFeatureA.geometry();
134 QgsFeatureIds lines = qgis::listToSet( spatialIndex.intersects( inGeom.boundingBox() ) );
135 if ( !lines.empty() )
136 {
137 // use prepared geometries for faster intersection tests
138 std::unique_ptr< QgsGeometryEngine > engine( QgsGeometry::createGeometryEngine( inGeom.constGet() ) );
139 engine->prepareGeometry();
140
142 request.setDestinationCrs( sourceA->sourceCrs(), context.transformContext() );
143 request.setSubsetOfAttributes( fieldIndicesB );
144
145 QgsFeature inFeatureB;
146 QgsFeatureIterator featuresB = sourceB->getFeatures( request );
147 while ( featuresB.nextFeature( inFeatureB ) )
148 {
149 if ( feedback->isCanceled() )
150 {
151 break;
152 }
153
154 QgsGeometry tmpGeom = inFeatureB.geometry();
155 if ( engine->intersects( tmpGeom.constGet() ) )
156 {
157 QgsMultiPointXY points;
158 QgsGeometry intersectGeom = inGeom.intersection( tmpGeom );
159 QgsAttributes outAttributes;
160 for ( int a : std::as_const( fieldIndicesA ) )
161 {
162 outAttributes.append( inFeatureA.attribute( a ) );
163 }
164 for ( int b : std::as_const( fieldIndicesB ) )
165 {
166 outAttributes.append( inFeatureB.attribute( b ) );
167 }
169 {
170 const QVector<QgsGeometry> geomCollection = intersectGeom.asGeometryCollection();
171 for ( const QgsGeometry &part : geomCollection )
172 {
173 if ( part.type() == Qgis::GeometryType::Point )
174 {
175 if ( part.isMultipart() )
176 {
177 points = part.asMultiPoint();
178 }
179 else
180 {
181 points.append( part.asPoint() );
182 }
183 }
184 }
185 }
186 else if ( intersectGeom.type() == Qgis::GeometryType::Point )
187 {
188 if ( intersectGeom.isMultipart() )
189 {
190 points = intersectGeom.asMultiPoint();
191 }
192 else
193 {
194 points.append( intersectGeom.asPoint() );
195 }
196 }
197 for ( const QgsPointXY &j : std::as_const( points ) )
198 {
199 outFeature.setGeometry( QgsGeometry::fromPointXY( j ) );
200 outFeature.setAttributes( outAttributes );
201 if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
202 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
203 }
204 }
205 }
206 }
207
208 feedback->setProgress( i * step );
209
210 }
211
212 QVariantMap outputs;
213 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
214 return outputs;
215}
216
218
219
@ 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.
Definition qgis.h:3176
@ GeometryCollection
GeometryCollection.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
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.
This class 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.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
A class to represent 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:27
QVector< QgsPointXY > QgsMultiPointXY
A collection of QgsPoints that share a common collection of attributes.
Definition qgsgeometry.h:80