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