QGIS API Documentation 3.41.0-Master (af5edcb665c)
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" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
52 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INTERSECT" ), QObject::tr( "Intersect layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
53
54 addParameter( new QgsProcessingParameterField(
55 QStringLiteral( "INPUT_FIELDS" ),
56 QObject::tr( "Input fields to keep (leave empty to keep all fields)" ), QVariant(),
57 QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Any,
58 true, true
59 ) );
60 addParameter( new QgsProcessingParameterField(
61 QStringLiteral( "INTERSECT_FIELDS" ),
62 QObject::tr( "Intersect fields to keep (leave empty to keep all fields)" ), QVariant(),
63 QStringLiteral( "INTERSECT" ), Qgis::ProcessingFieldParameterDataType::Any,
64 true, true
65 ) );
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
112 QString dest;
113 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, Qgis::WkbType::Point, sourceA->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
114 if ( !sink )
115 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
116
117 QgsSpatialIndex spatialIndex( sourceB->getFeatures( QgsFeatureRequest().setNoAttributes().setDestinationCrs( sourceA->sourceCrs(), context.transformContext() ) ), feedback );
118 QgsFeature outFeature;
119 QgsFeatureIterator features = sourceA->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( fieldIndicesA ) );
120 double step = sourceA->featureCount() > 0 ? 100.0 / sourceA->featureCount() : 1;
121 int i = 0;
122 QgsFeature inFeatureA;
123 while ( features.nextFeature( inFeatureA ) )
124 {
125 i++;
126 if ( feedback->isCanceled() )
127 {
128 break;
129 }
130
131 if ( !inFeatureA.hasGeometry() )
132 continue;
133
134 QgsGeometry inGeom = inFeatureA.geometry();
135 QgsFeatureIds lines = qgis::listToSet( spatialIndex.intersects( inGeom.boundingBox() ) );
136 if ( !lines.empty() )
137 {
138 // use prepared geometries for faster intersection tests
139 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( inGeom.constGet() ) );
140 engine->prepareGeometry();
141
143 request.setDestinationCrs( sourceA->sourceCrs(), context.transformContext() );
144 request.setSubsetOfAttributes( fieldIndicesB );
145
146 QgsFeature inFeatureB;
147 QgsFeatureIterator featuresB = sourceB->getFeatures( request );
148 while ( featuresB.nextFeature( inFeatureB ) )
149 {
150 if ( feedback->isCanceled() )
151 {
152 break;
153 }
154
155 QgsGeometry tmpGeom = inFeatureB.geometry();
156 if ( engine->intersects( tmpGeom.constGet() ) )
157 {
158 QgsMultiPointXY points;
159 QgsGeometry intersectGeom = inGeom.intersection( tmpGeom );
160 QgsAttributes outAttributes;
161 for ( int a : std::as_const( fieldIndicesA ) )
162 {
163 outAttributes.append( inFeatureA.attribute( a ) );
164 }
165 for ( int b : std::as_const( fieldIndicesB ) )
166 {
167 outAttributes.append( inFeatureB.attribute( b ) );
168 }
170 {
171 const QVector<QgsGeometry> geomCollection = intersectGeom.asGeometryCollection();
172 for ( const QgsGeometry &part : geomCollection )
173 {
174 if ( part.type() == Qgis::GeometryType::Point )
175 {
176 if ( part.isMultipart() )
177 {
178 points = part.asMultiPoint();
179 }
180 else
181 {
182 points.append( part.asPoint() );
183 }
184 }
185 }
186 }
187 else if ( intersectGeom.type() == Qgis::GeometryType::Point )
188 {
189 if ( intersectGeom.isMultipart() )
190 {
191 points = intersectGeom.asMultiPoint();
192 }
193 else
194 {
195 points.append( intersectGeom.asPoint() );
196 }
197 }
198 for ( const QgsPointXY &j : std::as_const( points ) )
199 {
200 outFeature.setGeometry( QgsGeometry::fromPointXY( j ) );
201 outFeature.setAttributes( outAttributes );
202 if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
203 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
204 }
205 }
206 }
207 }
208
209 feedback->setProgress( i * step );
210 }
211
212 sink->finalize();
213
214 QVariantMap outputs;
215 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
216 return outputs;
217}
218
@ 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:3430
@ 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.
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...
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