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