QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
Loading...
Searching...
No Matches
qgsalgorithmexportgeometryattributes.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmexportgeometryattributes.cpp
3 ---------------------
4 begin : February 2025
5 copyright : (C) 2025 by Alexander Bruy
6 email : alexander dot bruy 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 "qgscurve.h"
22#include "qgsunittypes.h"
23
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsExportGeometryAttributesAlgorithm::name() const
31{
32 return u"exportaddgeometrycolumns"_s;
33}
34
35QString QgsExportGeometryAttributesAlgorithm::displayName() const
36{
37 return QObject::tr( "Add geometry attributes" );
38}
39
40QStringList QgsExportGeometryAttributesAlgorithm::tags() const
41{
42 return QObject::tr( "export,add,information,measurements,areas,lengths,perimeters,latitudes,longitudes,x,y,z,extract,points,lines,polygons,sinuosity,fields" ).split( ',' );
43}
44
45QString QgsExportGeometryAttributesAlgorithm::group() const
46{
47 return QObject::tr( "Vector geometry" );
48}
49
50QString QgsExportGeometryAttributesAlgorithm::groupId() const
51{
52 return u"vectorgeometry"_s;
53}
54
55QString QgsExportGeometryAttributesAlgorithm::shortHelpString() const
56{
57 return QObject::tr(
58 "This algorithm computes geometric properties of the features in a vector layer. The algorithm generates a new "
59 "vector layer with the same content as the input one, but with additional attributes in its "
60 "attributes table, containing geometric measurements.\n\n"
61 "Depending on the geometry type of the vector layer, the attributes added to the table will "
62 "be different."
63 );
64}
65
66QString QgsExportGeometryAttributesAlgorithm::shortDescription() const
67{
68 return QObject::tr( "Computes geometric properties of the features in a vector layer." );
69}
70
71Qgis::ProcessingAlgorithmDocumentationFlags QgsExportGeometryAttributesAlgorithm::documentationFlags() const
72{
74}
75
76QgsExportGeometryAttributesAlgorithm *QgsExportGeometryAttributesAlgorithm::createInstance() const
77{
78 return new QgsExportGeometryAttributesAlgorithm();
79}
80
81void QgsExportGeometryAttributesAlgorithm::initAlgorithm( const QVariantMap & )
82{
83 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
84
85 const QStringList options = QStringList() << QObject::tr( "Cartesian Calculations in Layer's CRS" ) << QObject::tr( "Cartesian Calculations in Project's CRS" ) << QObject::tr( "Ellipsoidal Calculations" );
86 addParameter( new QgsProcessingParameterEnum( u"METHOD"_s, QObject::tr( "Calculate using" ), options, false, 0 ) );
87 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Added geometry info" ) ) );
88}
89
90bool QgsExportGeometryAttributesAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
91{
92 Q_UNUSED( parameters );
93
94 if ( QgsProject *project = context.project() )
95 {
96 mProjectCrs = project->crs();
97 }
98 return true;
99}
100
101QVariantMap QgsExportGeometryAttributesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
102{
103 QGS_MARK_ALGORITHM_SOURCE
104
105 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
106 if ( !source )
107 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
108
109 const int method = parameterAsEnum( parameters, u"METHOD"_s, context );
110
111 const Qgis::WkbType wkbType = source->wkbType();
112 QgsFields fields = source->fields();
113 QgsFields newFields;
114
115 bool exportZ = false;
116 bool exportM = false;
118 {
119 newFields.append( QgsField( u"area"_s, QMetaType::Type::Double ) );
120 newFields.append( QgsField( u"perimeter"_s, QMetaType::Type::Double ) );
121 }
123 {
124 newFields.append( QgsField( u"length"_s, QMetaType::Type::Double ) );
125 if ( !QgsWkbTypes::isMultiType( wkbType ) )
126 {
127 newFields.append( QgsField( u"straightdis"_s, QMetaType::Type::Double ) );
128 newFields.append( QgsField( u"sinuosity"_s, QMetaType::Type::Double ) );
129 }
130 }
131 else
132 {
133 if ( QgsWkbTypes::isMultiType( wkbType ) )
134 {
135 newFields.append( QgsField( u"numparts"_s, QMetaType::Type::Int ) );
136 }
137 else
138 {
139 newFields.append( QgsField( u"xcoord"_s, QMetaType::Type::Double ) );
140 newFields.append( QgsField( u"ycoord"_s, QMetaType::Type::Double ) );
141 if ( QgsWkbTypes::hasZ( wkbType ) )
142 {
143 newFields.append( QgsField( u"zcoord"_s, QMetaType::Type::Double ) );
144 exportZ = true;
145 }
146 if ( QgsWkbTypes::hasM( wkbType ) )
147 {
148 newFields.append( QgsField( u"mvalue"_s, QMetaType::Type::Double ) );
149 exportM = true;
150 }
151 }
152 }
153
154 fields = QgsProcessingUtils::combineFields( fields, newFields );
155
156 QString dest;
157 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, wkbType, source->sourceCrs() ) );
158 if ( !sink )
159 {
160 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
161 }
162
163 QgsCoordinateTransform transform;
164 mDa = QgsDistanceArea();
165
166 if ( method == 2 )
167 {
168 mDa.setSourceCrs( source->sourceCrs(), context.transformContext() );
169 mDa.setEllipsoid( context.ellipsoid() );
170 mDistanceConversionFactor = QgsUnitTypes::fromUnitToUnitFactor( mDa.lengthUnits(), context.distanceUnit() );
171 mAreaConversionFactor = QgsUnitTypes::fromUnitToUnitFactor( mDa.areaUnits(), context.areaUnit() );
172 }
173 else if ( method == 1 )
174 {
175 if ( !context.project() )
176 {
177 throw QgsProcessingException( QObject::tr( "No project is available in this context" ) );
178 }
179 transform = QgsCoordinateTransform( source->sourceCrs(), mProjectCrs, context.transformContext() );
180 }
181
182 QgsFeatureIterator it = source->getFeatures();
183 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0;
184 long i = 0;
185 QgsFeature f;
186
187 while ( it.nextFeature( f ) )
188 {
189 if ( feedback->isCanceled() )
190 {
191 break;
192 }
193
194 QgsFeature outputFeature( f );
195 QgsAttributes attrs = f.attributes();
196 QgsGeometry geom = f.geometry();
197
198 if ( !geom.isNull() )
199 {
200 if ( transform.isValid() )
201 {
202 try
203 {
204 geom.transform( transform );
205 }
206 catch ( QgsCsException &e )
207 {
208 throw QgsProcessingException( QObject::tr( "Could not transform feature to project's CRS: %1" ).arg( e.what() ) );
209 }
210 }
211
212 if ( geom.type() == Qgis::GeometryType::Point )
213 {
214 attrs << pointAttributes( geom, exportZ, exportM );
215 }
216 else if ( geom.type() == Qgis::GeometryType::Polygon )
217 {
218 attrs << polygonAttributes( geom );
219 }
220 else
221 {
222 attrs << lineAttributes( geom );
223 }
224 }
225
226 // ensure consistent count of attributes - otherwise null geometry features will have incorrect attribute
227 // length and provider may reject them
228 while ( attrs.size() < fields.size() )
229 {
230 attrs.append( QVariant() );
231 }
232
233 outputFeature.setAttributes( attrs );
234 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
235 {
236 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
237 }
238 else
239 {
240 feedback->featureAddedToSink( u"OUTPUT"_s );
241 }
242
243 i++;
244 feedback->setProgress( i * step );
245 }
246
247 sink->finalize();
248 feedback->featureSinkFinalized( u"OUTPUT"_s );
249
250 QVariantMap results;
251 results.insert( u"OUTPUT"_s, dest );
252 return results;
253}
254
255QgsAttributes QgsExportGeometryAttributesAlgorithm::pointAttributes( const QgsGeometry &geom, const bool exportZ, const bool exportM )
256{
257 QgsAttributes attrs;
258
259 if ( !geom.isMultipart() )
260 {
261 auto point = qgsgeometry_cast<const QgsPoint *>( geom.constGet() );
262 attrs.append( point->x() );
263 attrs.append( point->y() );
264 // add point Z/M
265 if ( exportZ )
266 {
267 attrs.append( point->z() );
268 }
269 if ( exportM )
270 {
271 attrs.append( point->m() );
272 }
273 }
275 {
276 attrs.append( collection->numGeometries() );
277 }
278 else
279 {
280 attrs.append( 0 );
281 }
282 return attrs;
283}
284
285QgsAttributes QgsExportGeometryAttributesAlgorithm::lineAttributes( const QgsGeometry &geom )
286{
287 QgsAttributes attrs;
288
289 if ( geom.isMultipart() )
290 {
291 attrs.append( mDistanceConversionFactor * mDa.measureLength( geom ) );
292 }
293 else
294 {
295 auto curve = qgsgeometry_cast<const QgsCurve *>( geom.constGet() );
296 const QgsPoint p1 = curve->startPoint();
297 const QgsPoint p2 = curve->endPoint();
298 const double straightDistance = mDistanceConversionFactor * mDa.measureLine( QgsPointXY( p1 ), QgsPointXY( p2 ) );
299 const double sinuosity = curve->sinuosity();
300 attrs.append( mDistanceConversionFactor * mDa.measureLength( geom ) );
301 attrs.append( straightDistance );
302 attrs.append( std::isnan( sinuosity ) ? QVariant() : sinuosity );
303 }
304
305 return attrs;
306}
307
308QgsAttributes QgsExportGeometryAttributesAlgorithm::polygonAttributes( const QgsGeometry &geom )
309{
310 const double area = mAreaConversionFactor * mDa.measureArea( geom );
311 const double perimeter = mDistanceConversionFactor * mDa.measurePerimeter( geom );
312
313 return QgsAttributes() << area << perimeter;
314}
315
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3749
@ Point
Points.
Definition qgis.h:380
@ Line
Lines.
Definition qgis.h:381
@ Polygon
Polygons.
Definition qgis.h:382
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3838
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3847
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:294
A vector of attributes.
Handles coordinate transforms between two coordinate systems.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
Custom exception class for Coordinate Reference System related exceptions.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
QString what() const
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.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:64
QgsGeometry geometry
Definition qgsfeature.h:66
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
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
int size() const
Returns number of items.
A geometry is the spatial representation of a feature.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Qgis::GeometryType type
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
Represents a 2D point.
Definition qgspointxy.h:62
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Qgis::AreaUnit areaUnit() const
Returns the area unit to use for area calculations.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
Qgis::DistanceUnit distanceUnit() const
Returns the distance unit to use for distance calculations.
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
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).
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:114
static Q_INVOKABLE double fromUnitToUnitFactor(Qgis::DistanceUnit fromUnit, Qgis::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Q_INVOKABLE bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static Q_INVOKABLE bool hasM(Qgis::WkbType type)
Tests whether a WKB type contains m values.
static Q_INVOKABLE bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.
T qgsgeometry_cast(QgsAbstractGeometry *geom)