27using namespace Qt::StringLiterals;
31QString QgsCalculateVectorOverlapsAlgorithm::name()
const
33 return u
"calculatevectoroverlaps"_s;
36QString QgsCalculateVectorOverlapsAlgorithm::displayName()
const
38 return QObject::tr(
"Overlap analysis" );
41QStringList QgsCalculateVectorOverlapsAlgorithm::tags()
const
43 return QObject::tr(
"vector,overlay,area,percentage,intersection" ).split(
',' );
46QString QgsCalculateVectorOverlapsAlgorithm::group()
const
48 return QObject::tr(
"Vector analysis" );
51QString QgsCalculateVectorOverlapsAlgorithm::groupId()
const
53 return u
"vectoranalysis"_s;
56void QgsCalculateVectorOverlapsAlgorithm::initAlgorithm(
const QVariantMap & )
64 addParameter( gridSize.release() );
67QIcon QgsCalculateVectorOverlapsAlgorithm::icon()
const
72QString QgsCalculateVectorOverlapsAlgorithm::svgIconPath()
const
77QString QgsCalculateVectorOverlapsAlgorithm::shortHelpString()
const
79 return QObject::tr(
"This algorithm calculates the area and percentage cover by which features from an input layer "
80 "are overlapped by features from a selection of overlay layers.\n\n"
81 "New attributes are added to the output layer reporting the total area of overlap and percentage of the input feature overlapped "
82 "by each of the selected overlay layers." );
85QString QgsCalculateVectorOverlapsAlgorithm::shortDescription()
const
87 return QObject::tr(
"Calculates the area and percentage cover by which features from an input layer "
88 "are overlapped by features from a selection of overlay layers." );
96QgsCalculateVectorOverlapsAlgorithm *QgsCalculateVectorOverlapsAlgorithm::createInstance()
const
98 return new QgsCalculateVectorOverlapsAlgorithm();
103 mSource.reset( parameterAsSource( parameters, u
"INPUT"_s, context ) );
107 mOutputFields = mSource->fields();
109 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u
"LAYERS"_s, context );
110 mOverlayerSources.reserve( layers.size() );
111 mLayerNames.reserve( layers.size() );
114 if (
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
116 mLayerNames << layer->name();
117 mOverlayerSources.emplace_back( std::make_unique<QgsVectorLayerFeatureSource>( vl ) );
119 newFields.
append(
QgsField( u
"%1_area"_s.arg( vl->name() ), QMetaType::Type::Double ) );
120 newFields.
append(
QgsField( u
"%1_pc"_s.arg( vl->name() ), QMetaType::Type::Double ) );
125 mOutputType = mSource->wkbType();
126 mCrs = mSource->sourceCrs();
127 mInputCount = mSource->featureCount();
128 mInputFeatures = mSource->getFeatures();
135 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u
"OUTPUT"_s, context, destId, mOutputFields, mOutputType, mCrs ) );
141 QList<QgsSpatialIndex> spatialIndices;
142 spatialIndices.reserve( mLayerNames.size() );
143 auto nameIt = mLayerNames.constBegin();
144 for (
auto sourceIt = mOverlayerSources.begin(); sourceIt != mOverlayerSources.end(); ++sourceIt, ++nameIt )
146 feedback->
pushInfo( QObject::tr(
"Preparing %1" ).arg( *nameIt ) );
156 if ( parameters.value( u
"GRID_SIZE"_s ).isValid() )
158 geometryParameters.
setGridSize( parameterAsDouble( parameters, u
"GRID_SIZE"_s, context ) );
162 const double step = mInputCount > 0 ? 100.0 / mInputCount : 0;
165 while ( mInputFeatures.nextFeature( feature ) )
175 double inputArea = 0;
187 bufferGeomEngine->prepareGeometry();
190 auto spatialIteratorIt = spatialIndices.begin();
191 for (
auto it = mOverlayerSources.begin(); it != mOverlayerSources.end(); ++it, ++spatialIteratorIt )
198 QVector<QgsGeometry> intersectingGeoms;
199 intersectingGeoms.reserve( matches.count() );
206 if ( bufferGeomEngine->intersects( overlayGeometry.
constGet() ) )
208 intersectingGeoms.append( overlayGeometry );
223 double overlayArea = 0;
226 overlayArea = da.
measureArea( overlayIntersection );
233 outAttributes.append( overlayArea );
234 outAttributes.append( 100 * overlayArea / inputArea );
240 for (
auto it = mOverlayerSources.begin(); it != mOverlayerSources.end(); ++it )
242 outAttributes.append( QVariant() );
243 outAttributes.append( QVariant() );
258 outputs.insert( u
"OUTPUT"_s, destId );
@ VectorPolygon
Vector polygon layers.
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
@ Double
Double/float values.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QString iconPath(const QString &iconFile)
Returns path to the desired icon file.
Custom exception class for Coordinate Reference System related exceptions.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
double measureArea(const QgsGeometry &geometry) const
Measures the area of a geometry.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
Wrapper for iterator of features from vector data provider or vector layer.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setInvalidGeometryCheck(Qgis::InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
QgsFeatureRequest & setInvalidGeometryCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is s...
@ 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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Encapsulates parameters under which a geometry operation is performed.
void setGridSize(double size)
Sets the grid size which will be used to snap vertices of a geometry.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
double area() const
Returns the planar, 2-dimensional area of the geometry.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters ¶meters=QgsGeometryParameters()) const
Returns a geometry representing the points shared by this geometry and other.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters ¶meters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
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...
Base class for all map layer types.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
std::function< void(const QgsFeature &) > invalidGeometryCallback(QgsFeatureSource *source=nullptr) const
Returns the callback function to use when encountering an invalid geometry and invalidGeometryCheck()...
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
Qgis::InvalidGeometryCheck invalidGeometryCheck() const
Returns the behavior used for checking invalid geometries in input layers.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A parameter for processing algorithms which accepts multiple map layers.
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.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
QList< QgsFeatureId > intersects(const QgsRectangle &rectangle) const
Returns a list of features with a bounding box which intersects the specified rectangle.
QgsGeometry geometry(QgsFeatureId id) const
Returns the stored geometry for the indexed feature with matching id.
Represents a vector layer which manages a vector based dataset.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QList< int > QgsAttributeList