QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
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
79QgsLineIntersectionAlgorithm *QgsLineIntersectionAlgorithm::createInstance() const
80{
81 return new QgsLineIntersectionAlgorithm();
82}
83
84QVariantMap QgsLineIntersectionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
85{
86 std::unique_ptr< QgsFeatureSource > sourceA( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
87 if ( !sourceA )
88 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
89
90 std::unique_ptr< QgsFeatureSource > sourceB( parameterAsSource( parameters, QStringLiteral( "INTERSECT" ), context ) );
91 if ( !sourceB )
92 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INTERSECT" ) ) );
93
94 const QStringList fieldsA = parameterAsStrings( parameters, QStringLiteral( "INPUT_FIELDS" ), context );
95 const QStringList fieldsB = parameterAsStrings( parameters, QStringLiteral( "INTERSECT_FIELDS" ), context );
96
97 QgsAttributeList fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( fieldsA, sourceA->fields() );
98 QgsAttributeList fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( fieldsB, sourceB->fields() );
99
100 QString intersectFieldsPrefix = parameterAsString( parameters, QStringLiteral( "INTERSECT_FIELDS_PREFIX" ), context );
102 QgsProcessingUtils::indicesToFields( fieldIndicesA, sourceA->fields() ),
103 QgsProcessingUtils::indicesToFields( fieldIndicesB, sourceB->fields() ),
104 intersectFieldsPrefix );
105
106 QString dest;
107 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, Qgis::WkbType::Point, sourceA->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
108 if ( !sink )
109 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
110
111 QgsSpatialIndex spatialIndex( sourceB->getFeatures( QgsFeatureRequest().setNoAttributes().setDestinationCrs( sourceA->sourceCrs(), context.transformContext() ) ), feedback );
112 QgsFeature outFeature;
113 QgsFeatureIterator features = sourceA->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( fieldIndicesA ) );
114 double step = sourceA->featureCount() > 0 ? 100.0 / sourceA->featureCount() : 1;
115 int i = 0;
116 QgsFeature inFeatureA;
117 while ( features.nextFeature( inFeatureA ) )
118 {
119 i++;
120 if ( feedback->isCanceled() )
121 {
122 break;
123 }
124
125 if ( !inFeatureA.hasGeometry() )
126 continue;
127
128 QgsGeometry inGeom = inFeatureA.geometry();
129 QgsFeatureIds lines = qgis::listToSet( spatialIndex.intersects( inGeom.boundingBox() ) );
130 if ( !lines.empty() )
131 {
132 // use prepared geometries for faster intersection tests
133 std::unique_ptr< QgsGeometryEngine > engine( QgsGeometry::createGeometryEngine( inGeom.constGet() ) );
134 engine->prepareGeometry();
135
137 request.setDestinationCrs( sourceA->sourceCrs(), context.transformContext() );
138 request.setSubsetOfAttributes( fieldIndicesB );
139
140 QgsFeature inFeatureB;
141 QgsFeatureIterator featuresB = sourceB->getFeatures( request );
142 while ( featuresB.nextFeature( inFeatureB ) )
143 {
144 if ( feedback->isCanceled() )
145 {
146 break;
147 }
148
149 QgsGeometry tmpGeom = inFeatureB.geometry();
150 if ( engine->intersects( tmpGeom.constGet() ) )
151 {
152 QgsMultiPointXY points;
153 QgsGeometry intersectGeom = inGeom.intersection( tmpGeom );
154 QgsAttributes outAttributes;
155 for ( int a : std::as_const( fieldIndicesA ) )
156 {
157 outAttributes.append( inFeatureA.attribute( a ) );
158 }
159 for ( int b : std::as_const( fieldIndicesB ) )
160 {
161 outAttributes.append( inFeatureB.attribute( b ) );
162 }
164 {
165 const QVector<QgsGeometry> geomCollection = intersectGeom.asGeometryCollection();
166 for ( const QgsGeometry &part : geomCollection )
167 {
168 if ( part.type() == Qgis::GeometryType::Point )
169 {
170 if ( part.isMultipart() )
171 {
172 points = part.asMultiPoint();
173 }
174 else
175 {
176 points.append( part.asPoint() );
177 }
178 }
179 }
180 }
181 else if ( intersectGeom.type() == Qgis::GeometryType::Point )
182 {
183 if ( intersectGeom.isMultipart() )
184 {
185 points = intersectGeom.asMultiPoint();
186 }
187 else
188 {
189 points.append( intersectGeom.asPoint() );
190 }
191 }
192 for ( const QgsPointXY &j : std::as_const( points ) )
193 {
194 outFeature.setGeometry( QgsGeometry::fromPointXY( j ) );
195 outFeature.setAttributes( outAttributes );
196 if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
197 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
198 }
199 }
200 }
201 }
202
203 feedback->setProgress( i * step );
204
205 }
206
207 QVariantMap outputs;
208 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
209 return outputs;
210}
211
213
214
@ VectorPoint
Vector point layers.
@ VectorLine
Vector line layers.
@ GeometryCollection
GeometryCollection.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
A vector of attributes.
Definition: qgsattributes.h:59
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:56
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:160
QgsGeometry geometry
Definition: qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:230
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Definition: qgsfeature.cpp:335
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:167
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:45
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:162
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
Definition: qgsgeometry.h:165
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.
Definition: qgsexception.h:83
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.
Definition: qgswkbtypes.h:628
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:37
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