QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
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#include "qgsunittypes.h"
21#include "qgscurve.h"
22
24
25QString QgsExportGeometryAttributesAlgorithm::name() const
26{
27 return QStringLiteral( "exportaddgeometrycolumns" );
28}
29
30QString QgsExportGeometryAttributesAlgorithm::displayName() const
31{
32 return QObject::tr( "Add geometry attributes" );
33}
34
35QStringList QgsExportGeometryAttributesAlgorithm::tags() const
36{
37 return QObject::tr( "export,add,information,measurements,areas,lengths,perimeters,latitudes,longitudes,x,y,z,extract,points,lines,polygons,sinuosity,fields" ).split( ',' );
38}
39
40QString QgsExportGeometryAttributesAlgorithm::group() const
41{
42 return QObject::tr( "Vector geometry" );
43}
44
45QString QgsExportGeometryAttributesAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorgeometry" );
48}
49
50QString QgsExportGeometryAttributesAlgorithm::shortHelpString() const
51{
52 return QObject::tr( "This algorithm computes geometric properties of the features in a vector layer. The algorithm generates a new "
53 "vector layer with the same content as the input one, but with additional attributes in its "
54 "attributes table, containing geometric measurements.\n\n"
55 "Depending on the geometry type of the vector layer, the attributes added to the table will "
56 "be different." );
57}
58
59QString QgsExportGeometryAttributesAlgorithm::shortDescription() const
60{
61 return QObject::tr( "Computes geometric properties of the features in a vector layer." );
62}
63
64QgsExportGeometryAttributesAlgorithm *QgsExportGeometryAttributesAlgorithm::createInstance() const
65{
66 return new QgsExportGeometryAttributesAlgorithm();
67}
68
69void QgsExportGeometryAttributesAlgorithm::initAlgorithm( const QVariantMap & )
70{
71 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
72
73 const QStringList options = QStringList()
74 << QObject::tr( "Cartesian Calculations in Layer's CRS" )
75 << QObject::tr( "Cartesian Calculations in Project's CRS" )
76 << QObject::tr( "Ellipsoidal Calculations" );
77 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Calculate using" ), options, false, 0 ) );
78 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Added geometry info" ) ) );
79}
80
81bool QgsExportGeometryAttributesAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
82{
83 Q_UNUSED( parameters );
84
85 mProjectCrs = context.project()->crs();
86 return true;
87}
88
89QVariantMap QgsExportGeometryAttributesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
90{
91 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
92 if ( !source )
93 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
94
95 const int method = parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context );
96
97 const Qgis::WkbType wkbType = source->wkbType();
98 QgsFields fields = source->fields();
99 QgsFields newFields;
100
101 bool exportZ = false;
102 bool exportM = false;
104 {
105 newFields.append( QgsField( QStringLiteral( "area" ), QMetaType::Type::Double ) );
106 newFields.append( QgsField( QStringLiteral( "perimeter" ), QMetaType::Type::Double ) );
107 }
109 {
110 newFields.append( QgsField( QStringLiteral( "length" ), QMetaType::Type::Double ) );
111 if ( !QgsWkbTypes::isMultiType( wkbType ) )
112 {
113 newFields.append( QgsField( QStringLiteral( "straightdis" ), QMetaType::Type::Double ) );
114 newFields.append( QgsField( QStringLiteral( "sinuosity" ), QMetaType::Type::Double ) );
115 }
116 }
117 else
118 {
119 if ( QgsWkbTypes::isMultiType( wkbType ) )
120 {
121 newFields.append( QgsField( QStringLiteral( "numparts" ), QMetaType::Type::Int ) );
122 }
123 else
124 {
125 newFields.append( QgsField( QStringLiteral( "xcoord" ), QMetaType::Type::Double ) );
126 newFields.append( QgsField( QStringLiteral( "ycoord" ), QMetaType::Type::Double ) );
127 if ( QgsWkbTypes::hasZ( wkbType ) )
128 {
129 newFields.append( QgsField( QStringLiteral( "zcoord" ), QMetaType::Type::Double ) );
130 exportZ = true;
131 }
132 if ( QgsWkbTypes::hasM( wkbType ) )
133 {
134 newFields.append( QgsField( QStringLiteral( "mvalue" ), QMetaType::Type::Double ) );
135 exportM = true;
136 }
137 }
138 }
139
140 fields = QgsProcessingUtils::combineFields( fields, newFields );
141
142 QString dest;
143 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, wkbType, source->sourceCrs() ) );
144 if ( !sink )
145 {
146 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
147 }
148
149 QgsCoordinateTransform transform;
150 mDa = QgsDistanceArea();
151
152 if ( method == 2 )
153 {
154 mDa.setSourceCrs( source->sourceCrs(), context.transformContext() );
155 mDa.setEllipsoid( context.ellipsoid() );
156 mDistanceConversionFactor = QgsUnitTypes::fromUnitToUnitFactor( mDa.lengthUnits(), context.distanceUnit() );
157 mAreaConversionFactor = QgsUnitTypes::fromUnitToUnitFactor( mDa.areaUnits(), context.areaUnit() );
158 }
159 else if ( method == 1 )
160 {
161 if ( !context.project() )
162 {
163 throw QgsProcessingException( QObject::tr( "No project is available in this context" ) );
164 }
165 transform = QgsCoordinateTransform( source->sourceCrs(), mProjectCrs, context.transformContext() );
166 }
167
168 QgsFeatureIterator it = source->getFeatures();
169 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0;
170 long i = 0;
171 QgsFeature f;
172
173 while ( it.nextFeature( f ) )
174 {
175 if ( feedback->isCanceled() )
176 {
177 break;
178 }
179
180 QgsFeature outputFeature( f );
181 QgsAttributes attrs = f.attributes();
182 QgsGeometry geom = f.geometry();
183
184 if ( !geom.isNull() )
185 {
186 if ( transform.isValid() )
187 {
188 try
189 {
190 geom.transform( transform );
191 }
192 catch ( QgsCsException &e )
193 {
194 throw QgsProcessingException( QObject::tr( "Could not transform feature to project's CRS: %1" ).arg( e.what() ) );
195 }
196 }
197
198 if ( geom.type() == Qgis::GeometryType::Point )
199 {
200 attrs << pointAttributes( geom, exportZ, exportM );
201 }
202 else if ( geom.type() == Qgis::GeometryType::Polygon )
203 {
204 attrs << polygonAttributes( geom );
205 }
206 else
207 {
208 attrs << lineAttributes( geom );
209 }
210 }
211
212 // ensure consistent count of attributes - otherwise null geometry features will have incorrect attribute
213 // length and provider may reject them
214 while ( attrs.size() < fields.size() )
215 {
216 attrs.append( QVariant() );
217 }
218
219 outputFeature.setAttributes( attrs );
220 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
221 {
222 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
223 }
224
225 i++;
226 feedback->setProgress( i * step );
227 }
228
229 sink->finalize();
230
231 QVariantMap results;
232 results.insert( QStringLiteral( "OUTPUT" ), dest );
233 return results;
234}
235
236QgsAttributes QgsExportGeometryAttributesAlgorithm::pointAttributes( const QgsGeometry &geom, const bool exportZ, const bool exportM )
237{
238 QgsAttributes attrs;
239
240 if ( !geom.isMultipart() )
241 {
242 auto point = qgsgeometry_cast<const QgsPoint *>( geom.constGet() );
243 attrs.append( point->x() );
244 attrs.append( point->y() );
245 // add point Z/M
246 if ( exportZ )
247 {
248 attrs.append( point->z() );
249 }
250 if ( exportM )
251 {
252 attrs.append( point->m() );
253 }
254 }
255 else
256 {
257 attrs.append( qgsgeometry_cast<const QgsGeometryCollection *>( geom.constGet() )->numGeometries() );
258 }
259 return attrs;
260}
261
262QgsAttributes QgsExportGeometryAttributesAlgorithm::lineAttributes( const QgsGeometry &geom )
263{
264 QgsAttributes attrs;
265
266 if ( geom.isMultipart() )
267 {
268 attrs.append( mDistanceConversionFactor * mDa.measureLength( geom ) );
269 }
270 else
271 {
272 auto curve = qgsgeometry_cast<const QgsCurve *>( geom.constGet() );
273 const QgsPoint p1 = curve->startPoint();
274 const QgsPoint p2 = curve->endPoint();
275 const double straightDistance = mDistanceConversionFactor * mDa.measureLine( QgsPointXY( p1 ), QgsPointXY( p2 ) );
276 const double sinuosity = curve->sinuosity();
277 attrs.append( mDistanceConversionFactor * mDa.measureLength( geom ) );
278 attrs.append( straightDistance );
279 attrs.append( std::isnan( sinuosity ) ? QVariant() : sinuosity );
280 }
281
282 return attrs;
283}
284
285QgsAttributes QgsExportGeometryAttributesAlgorithm::polygonAttributes( const QgsGeometry &geom )
286{
287 const double area = mAreaConversionFactor * mDa.measureArea( geom );
288 const double perimeter = mDistanceConversionFactor * mDa.measurePerimeter( geom );
289
290 return QgsAttributes() << area << perimeter;
291}
292
@ VectorAnyGeometry
Any vector layer with geometry.
@ Polygon
Polygons.
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:256
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:58
QgsAttributes attributes
Definition qgsfeature.h:67
QgsGeometry geometry
Definition qgsfeature.h:69
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
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:70
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:60
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
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.
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).
QgsCoordinateReferenceSystem crs
Definition qgsproject.h:112
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 bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.
static bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static bool hasM(Qgis::WkbType type)
Tests whether a WKB type contains m values.