QGIS API Documentation 3.41.0-Master (af5edcb665c)
Loading...
Searching...
No Matches
Classes | Public Member Functions | Static Public Member Functions | Properties | Friends | List of all members
QgsGeometry Class Reference

A geometry is the spatial representation of a feature. More...

#include <qgsgeometry.h>

Inheritance diagram for QgsGeometry:
Inheritance graph
[legend]

Classes

class  Error
 A geometry error. More...
 

Public Member Functions

 QgsGeometry ()
 
 QgsGeometry (const QgsGeometry &)
 Copy constructor will prompt a shallow copy of the geometry.
 
 QgsGeometry (QgsAbstractGeometry *geom)
 Creates a geometry from an abstract geometry object.
 
 QgsGeometry (std::unique_ptr< QgsAbstractGeometry > geom)
 Creates a geometry from an abstract geometry object.
 
virtual ~QgsGeometry ()
 
Qgis::GeometryOperationResult addPart (const QgsGeometry &newPart)
 Adds a new island polygon to a multipolygon feature.
 
Q_DECL_DEPRECATED Qgis::GeometryOperationResult addPart (const QgsPointSequence &points, Qgis::GeometryType geomType=Qgis::GeometryType::Unknown)
 Adds a new part to a the geometry.
 
Q_DECL_DEPRECATED Qgis::GeometryOperationResult addPart (const QVector< QgsPointXY > &points, Qgis::GeometryType geomType=Qgis::GeometryType::Unknown)
 Adds a new part to a the geometry.
 
Q_DECL_DEPRECATED Qgis::GeometryOperationResult addPart (QgsAbstractGeometry *part, Qgis::GeometryType geomType=Qgis::GeometryType::Unknown)
 Adds a new part to this geometry.
 
Qgis::GeometryOperationResult addPartV2 (const QgsPointSequence &points, Qgis::WkbType wkbType=Qgis::WkbType::Unknown)
 Adds a new part to a the geometry.
 
Qgis::GeometryOperationResult addPartV2 (const QVector< QgsPointXY > &points, Qgis::WkbType wkbType=Qgis::WkbType::Unknown)
 Adds a new part to a the geometry.
 
Qgis::GeometryOperationResult addPartV2 (QgsAbstractGeometry *part, Qgis::WkbType wkbType=Qgis::WkbType::Unknown)
 Adds a new part to this geometry.
 
Qgis::GeometryOperationResult addRing (const QVector< QgsPointXY > &ring)
 Adds a new ring to this geometry.
 
Qgis::GeometryOperationResult addRing (QgsCurve *ring)
 Adds a new ring to this geometry.
 
bool addTopologicalPoint (const QgsPoint &point, double snappingTolerance=1e-8, double segmentSearchEpsilon=1e-12)
 Adds a vertex to the segment which intersect point but don't already have a vertex there.
 
void adjacentVertices (int atVertex, int &beforeVertex, int &afterVertex) const
 Returns the indexes of the vertices before and after the given vertex index.
 
double angleAtVertex (int vertex) const
 Returns the bisector angle for this geometry at the specified vertex.
 
QgsGeometry applyDashPattern (const QVector< double > &pattern, Qgis::DashPatternLineEndingRule startRule=Qgis::DashPatternLineEndingRule::NoRule, Qgis::DashPatternLineEndingRule endRule=Qgis::DashPatternLineEndingRule::NoRule, Qgis::DashPatternSizeAdjustment adjustment=Qgis::DashPatternSizeAdjustment::ScaleBothDashAndGap, double patternOffset=0) const
 Applies a dash pattern to a geometry, returning a MultiLineString geometry which is the input geometry stroked along each line/ring with the specified pattern.
 
double area () const
 Returns the planar, 2-dimensional area of the geometry.
 
QVector< QgsGeometryasGeometryCollection () const
 Returns contents of the geometry as a list of geometries.
 
QString asJson (int precision=17) const
 Exports the geometry to a GeoJSON string.
 
virtual json asJsonObject (int precision=17) const
 Exports the geometry to a json object.
 
QgsMultiPointXY asMultiPoint () const
 Returns the contents of the geometry as a multi-point.
 
QgsMultiPolygonXY asMultiPolygon () const
 Returns the contents of the geometry as a multi-polygon.
 
QgsMultiPolylineXY asMultiPolyline () const
 Returns the contents of the geometry as a multi-linestring.
 
QgsPointXY asPoint () const
 Returns the contents of the geometry as a 2-dimensional point.
 
QgsPolygonXY asPolygon () const
 Returns the contents of the geometry as a polygon.
 
QgsPolylineXY asPolyline () const
 Returns the contents of the geometry as a polyline.
 
QPointF asQPointF () const
 Returns contents of the geometry as a QPointF if wkbType is WKBPoint, otherwise returns a null QPointF.
 
QPolygonF asQPolygonF () const
 Returns contents of the geometry as a QPolygonF.
 
QByteArray asWkb (QgsAbstractGeometry::WkbFlags flags=QgsAbstractGeometry::WkbFlags()) const
 Export the geometry to WKB.
 
Q_INVOKABLE QString asWkt (int precision=17) const
 Exports the geometry to WKT.
 
Q_DECL_DEPRECATED int avoidIntersections (const QList< QgsVectorLayer * > &avoidIntersectionsLayers, const QHash< QgsVectorLayer *, QSet< QgsFeatureId > > &ignoreFeatures=(QHash< QgsVectorLayer *, QSet< QgsFeatureId > >()))
 Modifies geometry to avoid intersections with the layers specified in project properties.
 
Qgis::GeometryOperationResult avoidIntersectionsV2 (const QList< QgsVectorLayer * > &avoidIntersectionsLayers, const QHash< QgsVectorLayer *, QSet< QgsFeatureId > > &ignoreFeatures=(QHash< QgsVectorLayer *, QSet< QgsFeatureId > >()))
 Modifies geometry to avoid intersections with the layers specified in project properties.
 
QgsRectangle boundingBox () const
 Returns the bounding box of the geometry.
 
QgsBox3D boundingBox3D () const
 Returns the 3D bounding box of the geometry.
 
bool boundingBoxIntersects (const QgsGeometry &geometry) const
 Returns true if the bounding box of this geometry intersects with the bounding box of another geometry.
 
bool boundingBoxIntersects (const QgsRectangle &rectangle) const
 Returns true if the bounding box of this geometry intersects with a rectangle.
 
QgsGeometry buffer (double distance, int segments) const
 Returns a buffer region around this geometry having the given width and with a specified number of segments used to approximate curves.
 
QgsGeometry buffer (double distance, int segments, Qgis::EndCapStyle endCapStyle, Qgis::JoinStyle joinStyle, double miterLimit) const
 Returns a buffer region around the geometry, with additional style options.
 
QgsGeometry centroid () const
 Returns the center of mass of a geometry.
 
QgsGeometry clipped (const QgsRectangle &rectangle)
 Clips the geometry using the specified rectangle.
 
double closestSegmentWithContext (const QgsPointXY &point, QgsPointXY &minDistPoint, int &nextVertexIndex, int *leftOrRightOfSegment=nullptr, double epsilon=DEFAULT_SEGMENT_EPSILON) const
 Searches for the closest segment of geometry to the given point.
 
QgsPointXY closestVertex (const QgsPointXY &point, int &closestVertexIndex, int &previousVertexIndex, int &nextVertexIndex, double &sqrDist) const
 Returns the vertex closest to the given point, the corresponding vertex index, squared distance snap point / target point and the indices of the vertices before and after the closest vertex.
 
double closestVertexWithContext (const QgsPointXY &point, int &atVertex) const
 Searches for the closest vertex in this geometry to the given point.
 
QVector< QgsGeometrycoerceToType (Qgis::WkbType type, double defaultZ=0, double defaultM=0) const
 Attempts to coerce this geometry into the specified destination type.
 
QgsGeometry combine (const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
 Returns a geometry representing all the points in this geometry and other (a union geometry operation).
 
QgsGeometry concaveHull (double targetPercent, bool allowHoles=false) const
 Returns a possibly concave polygon that contains all the points in the geometry.
 
QgsAbstractGeometry::const_part_iterator const_parts_begin () const
 Returns STL-style const iterator pointing to the first part of the geometry.
 
QgsAbstractGeometry::const_part_iterator const_parts_end () const
 Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
 
const QgsAbstractGeometryconstGet () const
 Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
 
QgsGeometryConstPartIterator constParts () const
 Returns Java-style iterator for traversal of parts of the geometry.
 
QgsGeometry constrainedDelaunayTriangulation () const
 Returns a constrained Delaunay triangulation for the vertices of the geometry.
 
bool contains (const QgsGeometry &geometry) const
 Returns true if the geometry completely contains another geometry.
 
bool contains (const QgsPointXY *p) const
 Returns true if the geometry contains the point p.
 
bool contains (double x, double y) const
 Returns true if the geometry contains the point at (x, y).
 
bool convertGeometryCollectionToSubclass (Qgis::GeometryType geomType)
 Converts geometry collection to a the desired geometry type subclass (multi-point, multi-linestring or multi-polygon).
 
bool convertToCurvedMultiType ()
 Converts a geometry into a multitype geometry of curve kind (when there is a corresponding curve type).
 
QgsGeometry convertToCurves (double distanceTolerance=1e-8, double angleTolerance=1e-8) const
 Attempts to convert a non-curved geometry into a curved geometry type (e.g.
 
bool convertToMultiType ()
 Converts single type geometry into multitype geometry e.g.
 
bool convertToSingleType ()
 Converts multi type geometry into single type geometry e.g.
 
void convertToStraightSegment (double tolerance=M_PI/180., QgsAbstractGeometry::SegmentationToleranceType toleranceType=QgsAbstractGeometry::MaximumAngle)
 Converts the geometry to straight line segments, if it is a curved geometry type.
 
QgsGeometry convertToType (Qgis::GeometryType destType, bool destMultipart=false) const
 Try to convert the geometry to the requested type.
 
QgsGeometry convexHull () const
 Returns the smallest convex polygon that contains all the points in the geometry.
 
bool crosses (const QgsGeometry &geometry) const
 Returns true if the geometry crosses another geometry.
 
QgsGeometry delaunayTriangulation (double tolerance=0.0, bool edgesOnly=false) const
 Returns the Delaunay triangulation for the vertices of the geometry.
 
bool deletePart (int partNum)
 Deletes part identified by the part number.
 
bool deleteRing (int ringNum, int partNum=0)
 Deletes a ring in polygon or multipolygon.
 
bool deleteVertex (int atVertex)
 Deletes the vertex at the given position number and item (first number is index 0)
 
QgsGeometry densifyByCount (int extraNodesPerSegment) const
 Returns a copy of the geometry which has been densified by adding the specified number of extra nodes within each segment of the geometry.
 
QgsGeometry densifyByDistance (double distance) const
 Densifies the geometry by adding regularly placed extra nodes inside each segment so that the maximum distance between any two nodes does not exceed the specified distance.
 
QgsGeometry difference (const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
 Returns a geometry representing the points making up this geometry that do not make up other.
 
bool disjoint (const QgsGeometry &geometry) const
 Returns true if the geometry is disjoint of another geometry.
 
double distance (const QgsGeometry &geom) const
 Returns the minimum distance between this geometry and another geometry.
 
double distanceToVertex (int vertex) const
 Returns the distance along this geometry from its first vertex to the specified vertex.
 
void draw (QPainter &p) const
 Draws the geometry onto a QPainter.
 
bool equals (const QgsGeometry &geometry) const
 Test if this geometry is exactly equal to another geometry.
 
QgsGeometry extendLine (double startDistance, double endDistance) const
 Extends a (multi)line geometry by extrapolating out the start or end of the line by a specified distance.
 
QgsGeometry extrude (double x, double y)
 Returns an extruded version of this geometry.
 
void filterVertices (const std::function< bool(const QgsPoint &) > &filter)
 Filters the vertices from the geometry in place, removing any which do not return true for the filter function check.
 
QgsGeometry forcePolygonClockwise () const
 Forces geometries to respect the exterior ring is clockwise, interior rings are counter-clockwise convention.
 
QgsGeometry forcePolygonCounterClockwise () const
 Forces geometries to respect the exterior ring is counter-clockwise, interior rings are clockwise convention.
 
QgsGeometry forceRHR () const
 Forces geometries to respect the Right-Hand-Rule, in which the area that is bounded by a polygon is to the right of the boundary.
 
double frechetDistance (const QgsGeometry &geom) const
 Returns the Fréchet distance between this geometry and geom, restricted to discrete points for both geometries.
 
double frechetDistanceDensify (const QgsGeometry &geom, double densifyFraction) const
 Returns the Fréchet distance between this geometry and geom, restricted to discrete points for both geometries.
 
void fromWkb (const QByteArray &wkb)
 Set the geometry, feeding in the buffer containing OGC Well-Known Binary.
 
void fromWkb (unsigned char *wkb, int length)
 Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length.
 
QgsAbstractGeometryget ()
 Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
 
double hausdorffDistance (const QgsGeometry &geom) const
 Returns the Hausdorff distance between this geometry and geom.
 
double hausdorffDistanceDensify (const QgsGeometry &geom, double densifyFraction) const
 Returns the Hausdorff distance between this geometry and geom.
 
bool insertVertex (const QgsPoint &point, int beforeVertex)
 Insert a new vertex before the given vertex index, ring and item (first number is index 0) If the requested vertex number (beforeVertex.back()) is greater than the last actual vertex on the requested ring and item, it is assumed that the vertex is to be appended instead of inserted.
 
bool insertVertex (double x, double y, int beforeVertex)
 Insert a new vertex before the given vertex index, ring and item (first number is index 0) If the requested vertex number (beforeVertex.back()) is greater than the last actual vertex on the requested ring and item, it is assumed that the vertex is to be appended instead of inserted.
 
QgsGeometry interpolate (double distance) const
 Returns an interpolated point on the geometry at the specified distance.
 
double interpolateAngle (double distance) const
 Returns the angle parallel to the linestring or polygon boundary at the specified distance along the geometry.
 
QgsGeometry intersection (const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
 Returns a geometry representing the points shared by this geometry and other.
 
bool intersects (const QgsGeometry &geometry) const
 Returns true if this geometry exactly intersects with another geometry.
 
bool intersects (const QgsRectangle &rectangle) const
 Returns true if this geometry exactly intersects with a rectangle.
 
bool isAxisParallelRectangle (double maximumDeviation, bool simpleRectanglesOnly=false) const
 Returns true if the geometry is a polygon that is almost an axis-parallel rectangle.
 
bool isEmpty () const
 Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geometries).
 
bool isGeosEqual (const QgsGeometry &) const
 Compares the geometry with another geometry using GEOS.
 
bool isGeosValid (Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const
 Checks validity of the geometry using GEOS.
 
bool isMultipart () const
 Returns true if WKB of the geometry is of WKBMulti* type.
 
bool isNull () const
 Returns true if the geometry is null (ie, contains no underlying geometry accessible via get() or constGet() ).
 
bool isPolygonClockwise () const
 Returns True if the Polygon is clockwise.
 
bool isPolygonCounterClockwise () const
 Returns True if the Polygon is counter-clockwise.
 
bool isSimple () const
 Determines whether the geometry is simple (according to OGC definition), i.e.
 
QgsGeometry largestEmptyCircle (double tolerance, const QgsGeometry &boundary=QgsGeometry()) const
 Constructs the Largest Empty Circle for a set of obstacle geometries, up to a specified tolerance.
 
QString lastError () const
 Returns an error string referring to the last error encountered either when this geometry was created or when an operation was performed on the geometry.
 
double length () const
 Returns the planar, 2-dimensional length of geometry.
 
double lineLocatePoint (const QgsGeometry &point) const
 Returns a distance representing the location along this linestring of the closest point on this linestring geometry to the specified point.
 
QgsGeometry makeDifference (const QgsGeometry &other) const
 Returns the geometry formed by modifying this geometry such that it does not intersect the other geometry.
 
int makeDifferenceInPlace (const QgsGeometry &other)
 Changes this geometry such that it does not intersect the other geometry.
 
QgsGeometry makeValid (Qgis::MakeValidMethod method=Qgis::MakeValidMethod::Linework, bool keepCollapsed=false) const
 Attempts to make an invalid geometry valid without losing vertices.
 
void mapToPixel (const QgsMapToPixel &mtp)
 Transforms the geometry from map units to pixels in place.
 
QgsGeometry mergeLines () const
 Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line strings.
 
QgsGeometry minimalEnclosingCircle (QgsPointXY &center, double &radius, unsigned int segments=36) const
 Returns the minimal enclosing circle for the geometry.
 
QgsGeometry minimalEnclosingCircle (unsigned int segments=36) const
 Returns the minimal enclosing circle for the geometry.
 
double minimumClearance () const
 Computes the minimum clearance of a geometry.
 
QgsGeometry minimumClearanceLine () const
 Returns a LineString whose endpoints define the minimum clearance of a geometry.
 
QgsGeometry minimumWidth () const
 Returns a linestring geometry which represents the minimum diameter of the geometry.
 
bool moveVertex (const QgsPoint &p, int atVertex)
 Moves the vertex at the given position number and item (first number is index 0) to the given coordinates.
 
bool moveVertex (double x, double y, int atVertex)
 Moves the vertex at the given position number and item (first number is index 0) to the given coordinates.
 
QgsGeometry nearestPoint (const QgsGeometry &other) const
 Returns the nearest (closest) point on this geometry to another geometry.
 
QgsGeometry node () const
 Returns a (Multi)LineString representing the fully noded version of a collection of linestrings.
 
void normalize ()
 Reorganizes the geometry into a normalized form (or "canonical" form).
 
QgsGeometry offsetCurve (double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit) const
 Returns an offset line at a given distance and side from an input line.
 
 operator QVariant () const
 Allows direct construction of QVariants from geometry.
 
QgsGeometryoperator= (QgsGeometry const &rhs)
 Creates a shallow copy of the geometry.
 
QgsGeometry orientedMinimumBoundingBox () const
 Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated rectangle which fully encompasses the geometry.
 
QgsGeometry orientedMinimumBoundingBox (double &area, double &angle, double &width, double &height) const
 Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated rectangle which fully encompasses the geometry.
 
QgsGeometry orthogonalize (double tolerance=1.0E-8, int maxIterations=1000, double angleThreshold=15.0) const
 Attempts to orthogonalize a line or polygon geometry by shifting vertices to make the geometries angles either right angles or flat lines.
 
bool overlaps (const QgsGeometry &geometry) const
 Returns true if the geometry overlaps another geometry.
 
QgsGeometryPartIterator parts ()
 Returns Java-style iterator for traversal of parts of the geometry.
 
QgsAbstractGeometry::part_iterator parts_begin ()
 Returns STL-style iterator pointing to the first part of the geometry.
 
QgsAbstractGeometry::part_iterator parts_end ()
 Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
 
QgsGeometry pointOnSurface () const
 Returns a point guaranteed to lie on the surface of a geometry.
 
QgsGeometry poleOfInaccessibility (double precision, double *distanceToBoundary=nullptr) const
 Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal point from the boundary of the surface.
 
Qgis::AngularDirection polygonOrientation () const
 Returns the orientation of the polygon.
 
QVector< QgsPointXYrandomPointsInPolygon (int count, const std::function< bool(const QgsPointXY &) > &acceptPoint, unsigned long seed=0, QgsFeedback *feedback=nullptr, int maxTriesPerPoint=0) const
 Returns a list of count random points generated inside a (multi)polygon geometry (if acceptPoint is specified, and restrictive, the number of points returned may be less than count).
 
QVector< QgsPointXYrandomPointsInPolygon (int count, unsigned long seed=0, QgsFeedback *feedback=nullptr) const
 Returns a list of count random points generated inside a (multi)polygon geometry.
 
bool removeDuplicateNodes (double epsilon=4 *std::numeric_limits< double >::epsilon(), bool useZValues=false)
 Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerate geometry.
 
QgsGeometry removeInteriorRings (double minimumAllowedArea=-1) const
 Removes the interior rings from a (multi)polygon geometry.
 
bool requiresConversionToStraightSegments () const
 Returns true if the geometry is a curved geometry type which requires conversion to display as straight line segments.
 
Qgis::GeometryOperationResult reshapeGeometry (const QgsLineString &reshapeLineString)
 Replaces a part of this geometry with another line.
 
Qgis::GeometryOperationResult rotate (double rotation, const QgsPointXY &center)
 Rotate this geometry around the Z axis.
 
QgsGeometry roundWaves (double wavelength, double amplitude, bool strictWavelength=false) const
 Constructs rounded (sine-like) waves along the boundary of the geometry, with the specified wavelength and amplitude.
 
QgsGeometry roundWavesRandomized (double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
 Constructs randomized rounded (sine-like) waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
 
void set (QgsAbstractGeometry *geometry)
 Sets the underlying geometry store.
 
QgsGeometry sharedPaths (const QgsGeometry &other) const
 Find paths shared between the two given lineal geometries (this and other).
 
QgsGeometry shortestLine (const QgsGeometry &other) const
 Returns the shortest line joining this geometry to another geometry.
 
QgsGeometry simplify (double tolerance) const
 Returns a simplified version of this geometry using a specified tolerance value.
 
QgsGeometry simplifyCoverageVW (double tolerance, bool preserveBoundary) const
 Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geometry) to apply a Visvalingam–Whyatt simplification to the edges, reducing complexity in proportion with the provided tolerance, while retaining a valid coverage (no edges will cross or touch after the simplification).
 
QgsGeometry singleSidedBuffer (double distance, int segments, Qgis::BufferSide side, Qgis::JoinStyle joinStyle=Qgis::JoinStyle::Round, double miterLimit=2.0) const
 Returns a single sided buffer for a (multi)line geometry.
 
QgsGeometry smooth (unsigned int iterations=1, double offset=0.25, double minimumDistance=-1.0, double maxAngle=180.0) const
 Smooths a geometry by rounding off corners using the Chaikin algorithm.
 
QgsGeometry snappedToGrid (double hSpacing, double vSpacing, double dSpacing=0, double mSpacing=0) const
 Returns a new geometry with all points or vertices snapped to the closest point of the grid.
 
Qgis::GeometryOperationResult splitGeometry (const QgsCurve *curve, QVector< QgsGeometry > &newGeometries, bool preserveCircular, bool topological, QgsPointSequence &topologyTestPoints, bool splitFeature=true)
 Splits this geometry according to a given curve.
 
Qgis::GeometryOperationResult splitGeometry (const QgsPointSequence &splitLine, QVector< QgsGeometry > &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, bool splitFeature=true, bool skipIntersectionTest=false)
 Splits this geometry according to a given line.
 
Q_DECL_DEPRECATED Qgis::GeometryOperationResult splitGeometry (const QVector< QgsPointXY > &splitLine, QVector< QgsGeometry > &newGeometries, bool topological, QVector< QgsPointXY > &topologyTestPoints, bool splitFeature=true)
 Splits this geometry according to a given line.
 
double sqrDistToVertexAt (QgsPointXY &point, int atVertex) const
 Returns the squared Cartesian distance between the given point to the given vertex index (vertex at the given position number, ring and item (first number is index 0))
 
QgsGeometry squareWaves (double wavelength, double amplitude, bool strictWavelength=false) const
 Constructs square waves along the boundary of the geometry, with the specified wavelength and amplitude.
 
QgsGeometry squareWavesRandomized (double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
 Constructs randomized square waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
 
QgsGeometry subdivide (int maxNodes=256, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
 Subdivides the geometry.
 
QgsGeometry symDifference (const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
 Returns a geometry representing the points making up this geometry that do not make up other.
 
QgsGeometry taperedBuffer (double startWidth, double endWidth, int segments) const
 Calculates a variable width buffer ("tapered buffer") for a (multi)curve geometry.
 
bool toggleCircularAtVertex (int atVertex)
 Converts the vertex at the given position from/to circular.
 
bool touches (const QgsGeometry &geometry) const
 Returns true if the geometry touches another geometry.
 
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.
 
Qgis::GeometryOperationResult transform (const QTransform &t, double zTranslate=0.0, double zScale=1.0, double mTranslate=0.0, double mScale=1.0)
 Transforms the x and y components of the geometry using a QTransform object t.
 
void transformVertices (const std::function< QgsPoint(const QgsPoint &) > &transform)
 Transforms the vertices from the geometry in place, applying the transform function to every vertex.
 
Qgis::GeometryOperationResult translate (double dx, double dy, double dz=0.0, double dm=0.0)
 Translates this geometry by dx, dy, dz and dm.
 
QgsGeometry triangularWaves (double wavelength, double amplitude, bool strictWavelength=false) const
 Constructs triangular waves along the boundary of the geometry, with the specified wavelength and amplitude.
 
QgsGeometry triangularWavesRandomized (double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
 Constructs randomized triangular waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
 
Qgis::GeometryType type () const
 Returns type of the geometry as a Qgis::GeometryType.
 
QgsGeometry unionCoverage () const
 Optimized union algorithm for polygonal inputs that are correctly noded and do not overlap.
 
Qgis::CoverageValidityResult validateCoverage (double gapWidth, QgsGeometry *invalidEdges=nullptr) const
 Analyze a coverage (represented as a collection of polygonal geometry with exactly matching edge geometry) to find places where the assumption of exactly matching edges is not met.
 
void validateGeometry (QVector< QgsGeometry::Error > &errors, Qgis::GeometryValidationEngine method=Qgis::GeometryValidationEngine::QgisInternal, Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const
 Validates geometry and produces a list of geometry errors.
 
QgsGeometry variableWidthBufferByM (int segments) const
 Calculates a variable width buffer for a (multi)linestring geometry, where the width at each node is taken from the linestring m values.
 
QgsPoint vertexAt (int atVertex) const
 Returns coordinates of a vertex.
 
bool vertexIdFromVertexNr (int number, QgsVertexId &id) const
 Calculates the vertex ID from a vertex number.
 
int vertexNrFromVertexId (QgsVertexId id) const
 Returns the vertex number corresponding to a vertex id.
 
QgsVertexIterator vertices () const
 Returns a read-only, Java-style iterator for traversal of vertices of all the geometry, including all geometry parts and rings.
 
QgsAbstractGeometry::vertex_iterator vertices_begin () const
 Returns STL-style iterator pointing to the first vertex of the geometry.
 
QgsAbstractGeometry::vertex_iterator vertices_end () const
 Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
 
QgsGeometry voronoiDiagram (const QgsGeometry &extent=QgsGeometry(), double tolerance=0.0, bool edgesOnly=false) const
 Creates a Voronoi diagram for the nodes contained within the geometry.
 
bool within (const QgsGeometry &geometry) const
 Returns true if the geometry is completely within another geometry.
 
int wkbSize (QgsAbstractGeometry::WkbFlags flags=QgsAbstractGeometry::WkbFlags()) const
 Returns the length of the QByteArray returned by asWkb()
 
Qgis::WkbType wkbType () const
 Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
 

Static Public Member Functions

static QgsGeometry collectGeometry (const QVector< QgsGeometry > &geometries)
 Creates a new multipart geometry from a list of QgsGeometry objects.
 
static bool compare (const QgsMultiPolygonXY &p1, const QgsMultiPolygonXY &p2, double epsilon=4 *std::numeric_limits< double >::epsilon())
 Compares two multipolygons for equality within a specified tolerance.
 
static bool compare (const QgsPolygonXY &p1, const QgsPolygonXY &p2, double epsilon=4 *std::numeric_limits< double >::epsilon())
 Compares two polygons for equality within a specified tolerance.
 
static bool compare (const QgsPolylineXY &p1, const QgsPolylineXY &p2, double epsilon=4 *std::numeric_limits< double >::epsilon())
 Compares two polylines for equality within a specified tolerance.
 
static void convertPointList (const QgsPointSequence &input, QVector< QgsPointXY > &output)
 Downgrades a point list from QgsPoint to QgsPointXY.
 
static void convertPointList (const QVector< QgsPointXY > &input, QgsPointSequence &output)
 Upgrades a point list from QgsPointXY to QgsPoint.
 
static QgsGeometryEnginecreateGeometryEngine (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 grid.
 
static Q_DECL_DEPRECATED QgsPolygonXY createPolygonFromQPolygonF (const QPolygonF &polygon)
 Creates a QgsPolygonXYfrom a QPolygonF.
 
static Q_DECL_DEPRECATED QgsPolylineXY createPolylineFromQPolygonF (const QPolygonF &polygon)
 Creates a QgsPolylineXY from a QPolygonF.
 
static QgsGeometry createWedgeBuffer (const QgsPoint &center, double azimuth, double angularWidth, double outerRadius, double innerRadius=0)
 Creates a wedge shaped buffer from a center point.
 
static QgsGeometry createWedgeBufferFromAngles (const QgsPoint &center, double startAngle, double endAngle, double outerRadius, double innerRadius=0)
 Creates a wedge shaped buffer from a center point.
 
static QgsGeometry fromBox3D (const QgsBox3D &box)
 Creates a new geometry from a QgsBox3D object Returns a 2D polygon geometry if the box is purely 2d, otherwise returns a polyhedral surface geometry.
 
static QgsGeometry fromMultiPointXY (const QgsMultiPointXY &multipoint)
 Creates a new geometry from a QgsMultiPointXY object.
 
static QgsGeometry fromMultiPolygonXY (const QgsMultiPolygonXY &multipoly)
 Creates a new geometry from a QgsMultiPolygonXY.
 
static QgsGeometry fromMultiPolylineXY (const QgsMultiPolylineXY &multiline)
 Creates a new geometry from a QgsMultiPolylineXY object.
 
static QgsGeometry fromPoint (const QgsPoint &point)
 Creates a new geometry from a QgsPoint object.
 
static QgsGeometry fromPointXY (const QgsPointXY &point)
 Creates a new geometry from a QgsPointXY object.
 
static QgsGeometry fromPolygonXY (const QgsPolygonXY &polygon)
 Creates a new geometry from a QgsPolygonXY.
 
static QgsGeometry fromPolyline (const QgsPolyline &polyline)
 Creates a new LineString geometry from a list of QgsPoint points.
 
static QgsGeometry fromPolylineXY (const QgsPolylineXY &polyline)
 Creates a new LineString geometry from a list of QgsPointXY points.
 
static QgsGeometry fromQPointF (QPointF point)
 Construct geometry from a QPointF.
 
static QgsGeometry fromQPolygonF (const QPolygonF &polygon)
 Construct geometry from a QPolygonF.
 
static QgsGeometry fromRect (const QgsRectangle &rect)
 Creates a new geometry from a QgsRectangle.
 
static Q_INVOKABLE QgsGeometry fromWkt (const QString &wkt)
 Creates a new geometry from a WKT string.
 
static QgsGeometry polygonize (const QVector< QgsGeometry > &geometries)
 Creates a GeometryCollection geometry containing possible polygons formed from the constituent linework of a set of geometries.
 
static QgsGeometry unaryUnion (const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
 Compute the unary union on a list of geometries.
 

Properties

bool isNull
 
Qgis::GeometryType type
 

Friends

class QgsInternalGeometryEngine
 

Detailed Description

A geometry is the spatial representation of a feature.

QgsGeometry acts as a generic container for geometry objects. QgsGeometry objects are implicitly shared, so making copies of geometries is inexpensive. The geometry container class can also be stored inside a QVariant object.

The actual geometry representation is stored as a QgsAbstractGeometry within the container, and can be accessed via the get() method or set using the set() method. This gives access to the underlying raw geometry primitive, such as the point, line, polygon, curve or other geometry subclasses.

Note
QgsGeometry objects are inherently Cartesian/planar geometries. They have no concept of geodesy, and none of the methods or properties exposed from the QgsGeometry API (or QgsAbstractGeometry subclasses) utilize geodesic calculations. Accordingly, properties like length() and area() or spatial operations like buffer() are always calculated using strictly Cartesian mathematics. In contrast, the QgsDistanceArea class exposes methods for working with geodesic calculations and spatial operations on geometries, and should be used whenever calculations which account for the curvature of the Earth (or any other celestial body) are required.

Definition at line 161 of file qgsgeometry.h.

Constructor & Destructor Documentation

◆ QgsGeometry() [1/4]

QgsGeometry::QgsGeometry ( )

Definition at line 61 of file qgsgeometry.cpp.

◆ QgsGeometry() [2/4]

QgsGeometry::QgsGeometry ( const QgsGeometry other)

Copy constructor will prompt a shallow copy of the geometry.

Definition at line 83 of file qgsgeometry.cpp.

◆ QgsGeometry() [3/4]

QgsGeometry::QgsGeometry ( QgsAbstractGeometry geom)
explicit

Creates a geometry from an abstract geometry object.

Ownership of geom is transferred.

Definition at line 72 of file qgsgeometry.cpp.

◆ QgsGeometry() [4/4]

QgsGeometry::QgsGeometry ( std::unique_ptr< QgsAbstractGeometry geom)
explicit

Creates a geometry from an abstract geometry object.

Ownership of geom is transferred.

Note
Not available in Python bindings

Definition at line 78 of file qgsgeometry.cpp.

◆ ~QgsGeometry()

QgsGeometry::~QgsGeometry ( )
virtual

Definition at line 66 of file qgsgeometry.cpp.

Member Function Documentation

◆ addPart() [1/4]

Qgis::GeometryOperationResult QgsGeometry::addPart ( const QgsGeometry newPart)

Adds a new island polygon to a multipolygon feature.

Returns
OperationResult a result code: success or reason of failure
Note
available in python bindings as addPartGeometry

Definition at line 1076 of file qgsgeometry.cpp.

◆ addPart() [2/4]

Qgis::GeometryOperationResult QgsGeometry::addPart ( const QgsPointSequence points,
Qgis::GeometryType  geomType = Qgis::GeometryType::Unknown 
)

Adds a new part to a the geometry.

Parameters
pointspoints describing part to add
geomTypedefault geometry type to create if no existing geometry
Returns
OperationResult a result code: success or reason of failure
Deprecated:
QGIS 3.38. Will be removed in QGIS 4.0. Use addPartV2 which accepts Qgis::WkbType geometry type instead of Qgis::GeometryType.

Definition at line 974 of file qgsgeometry.cpp.

◆ addPart() [3/4]

Qgis::GeometryOperationResult QgsGeometry::addPart ( const QVector< QgsPointXY > &  points,
Qgis::GeometryType  geomType = Qgis::GeometryType::Unknown 
)

Adds a new part to a the geometry.

Parameters
pointspoints describing part to add
geomTypedefault geometry type to create if no existing geometry
Returns
OperationResult a result code: success or reason of failure
Deprecated:
QGIS 3.38. Will be removed in QGIS 4.0. Use addPartV2 which accepts Qgis::WkbType geometry type instead of Qgis::GeometryType.

Definition at line 958 of file qgsgeometry.cpp.

◆ addPart() [4/4]

Adds a new part to this geometry.

Parameters
partpart to add (ownership is transferred)
geomTypedefault geometry type to create if no existing geometry
Returns
OperationResult a result code: success or reason of failure
Deprecated:
QGIS 3.38. Will be removed in QGIS 4.0. Use addPartV2 which accepts Qgis::WkbType geometry type instead of Qgis::GeometryType.

Definition at line 1008 of file qgsgeometry.cpp.

◆ addPartV2() [1/3]

Qgis::GeometryOperationResult QgsGeometry::addPartV2 ( const QgsPointSequence points,
Qgis::WkbType  wkbType = Qgis::WkbType::Unknown 
)

Adds a new part to a the geometry.

Parameters
pointspoints describing part to add
wkbTypedefault WKB type to create if no existing geometry
Returns
OperationResult a result code: success or reason of failure
Since
QGIS 3.38

Definition at line 992 of file qgsgeometry.cpp.

◆ addPartV2() [2/3]

Qgis::GeometryOperationResult QgsGeometry::addPartV2 ( const QVector< QgsPointXY > &  points,
Qgis::WkbType  wkbType = Qgis::WkbType::Unknown 
)

Adds a new part to a the geometry.

Parameters
pointspoints describing part to add
wkbTypedefault WKB type to create if no existing geometry
Returns
OperationResult a result code: success or reason of failure
Since
QGIS 3.38

Definition at line 967 of file qgsgeometry.cpp.

◆ addPartV2() [3/3]

Qgis::GeometryOperationResult QgsGeometry::addPartV2 ( QgsAbstractGeometry part,
Qgis::WkbType  wkbType = Qgis::WkbType::Unknown 
)

Adds a new part to this geometry.

Parameters
partpart to add (ownership is transferred)
wkbTypedefault WKB type to create if no existing geometry
Returns
OperationResult a result code: success or reason of failure
Since
QGIS 3.38

Definition at line 1038 of file qgsgeometry.cpp.

◆ addRing() [1/2]

Qgis::GeometryOperationResult QgsGeometry::addRing ( const QVector< QgsPointXY > &  ring)

Adds a new ring to this geometry.

This makes only sense for polygon and multipolygons.

Parameters
ringThe ring to be added
Returns
OperationResult a result code: success or reason of failure

Definition at line 939 of file qgsgeometry.cpp.

◆ addRing() [2/2]

Qgis::GeometryOperationResult QgsGeometry::addRing ( QgsCurve ring)

Adds a new ring to this geometry.

This makes only sense for polygon and multipolygons.

Parameters
ringThe ring to be added
Returns
OperationResult a result code: success or reason of failure

Definition at line 945 of file qgsgeometry.cpp.

◆ addTopologicalPoint()

bool QgsGeometry::addTopologicalPoint ( const QgsPoint point,
double  snappingTolerance = 1e-8,
double  segmentSearchEpsilon = 1e-12 
)

Adds a vertex to the segment which intersect point but don't already have a vertex there.

Closest segment is identified using segmentSearchEpsilon. If a vertex already exists within snappingTolearnceDistance, no additional vertex is inserted.

Returns
true if point was added, false otherwise
Since
QGIS 3.38

Definition at line 816 of file qgsgeometry.cpp.

◆ adjacentVertices()

void QgsGeometry::adjacentVertices ( int  atVertex,
int &  beforeVertex,
int &  afterVertex 
) const

Returns the indexes of the vertices before and after the given vertex index.

This function takes into account the following factors:

  • If the given vertex index is at the end of a linestring, the adjacent index will be -1 (for "no adjacent vertex")
  • If the given vertex index is at the end of a linear ring (such as in a polygon), the adjacent index will take into account the first vertex is equal to the last vertex (and will skip equal vertex positions).

Definition at line 591 of file qgsgeometry.cpp.

◆ angleAtVertex()

double QgsGeometry::angleAtVertex ( int  vertex) const

Returns the bisector angle for this geometry at the specified vertex.

Parameters
vertexvertex index to calculate bisector angle at
Returns
bisector angle, in radians clockwise from north
See also
interpolateAngle()

Definition at line 575 of file qgsgeometry.cpp.

◆ applyDashPattern()

QgsGeometry QgsGeometry::applyDashPattern ( const QVector< double > &  pattern,
Qgis::DashPatternLineEndingRule  startRule = Qgis::DashPatternLineEndingRule::NoRule,
Qgis::DashPatternLineEndingRule  endRule = Qgis::DashPatternLineEndingRule::NoRule,
Qgis::DashPatternSizeAdjustment  adjustment = Qgis::DashPatternSizeAdjustment::ScaleBothDashAndGap,
double  patternOffset = 0 
) const

Applies a dash pattern to a geometry, returning a MultiLineString geometry which is the input geometry stroked along each line/ring with the specified pattern.

The startRule and endRule options can be set to control how the dash pattern is adjusted at line endings. If a startRule or endRule is set, the adjustment option defines whether both dash and gaps, or only dash or gap sizes are adjusted to apply the rules.

The patternOffset option specifies how far along the pattern the result should start at. The offset is applied AFTER any start/end rules are applied.

Since
QGIS 3.24

Definition at line 1478 of file qgsgeometry.cpp.

◆ area()

double QgsGeometry::area ( ) const

Returns the planar, 2-dimensional area of the geometry.

Warning
QgsGeometry objects are inherently Cartesian/planar geometries, and the area returned by this method is calculated using strictly Cartesian mathematics. In contrast, the QgsDistanceArea class exposes methods for calculating the areas of geometries using geodesic calculations which account for the curvature of the Earth (or any other celestial body).
See also
length()

Definition at line 2229 of file qgsgeometry.cpp.

◆ asGeometryCollection()

QVector< QgsGeometry > QgsGeometry::asGeometryCollection ( ) const

Returns contents of the geometry as a list of geometries.

Definition at line 3192 of file qgsgeometry.cpp.

◆ asJson()

QString QgsGeometry::asJson ( int  precision = 17) const

Exports the geometry to a GeoJSON string.

Definition at line 1683 of file qgsgeometry.cpp.

◆ asJsonObject()

json QgsGeometry::asJsonObject ( int  precision = 17) const
virtual

Exports the geometry to a json object.

Note
not available in Python bindings
Since
QGIS 3.8

Definition at line 1688 of file qgsgeometry.cpp.

◆ asMultiPoint()

QgsMultiPointXY QgsGeometry::asMultiPoint ( ) const

Returns the contents of the geometry as a multi-point.

Any z or m values present in the geometry will be discarded.

Warning
If the geometry is not a multi-point type, an empty list will be returned.

Definition at line 2108 of file qgsgeometry.cpp.

◆ asMultiPolygon()

QgsMultiPolygonXY QgsGeometry::asMultiPolygon ( ) const

Returns the contents of the geometry as a multi-polygon.

Any z or m values present in the geometry will be discarded. If the geometry is a curved polygon type (such as a MultiSurface), it will be automatically segmentized.

Warning
If the geometry is not a multi-polygon (or multi-curve polygon) type, an empty list will be returned.

Definition at line 2185 of file qgsgeometry.cpp.

◆ asMultiPolyline()

QgsMultiPolylineXY QgsGeometry::asMultiPolyline ( ) const

Returns the contents of the geometry as a multi-linestring.

Any z or m values present in the geometry will be discarded. If the geometry is a curved line type (such as a MultiCurve), it will be automatically segmentized.

Warning
If the geometry is not a multi-linestring (or multi-curve linestring) type, an empty list will be returned.

Definition at line 2132 of file qgsgeometry.cpp.

◆ asPoint()

QgsPointXY QgsGeometry::asPoint ( ) const

Returns the contents of the geometry as a 2-dimensional point.

Any z or m values present in the geometry will be discarded.

Warning
If the geometry is not a single-point type (or a multipoint containing a single point) an empty QgsPointXY() will be returned.

Definition at line 2011 of file qgsgeometry.cpp.

◆ asPolygon()

QgsPolygonXY QgsGeometry::asPolygon ( ) const

Returns the contents of the geometry as a polygon.

Any z or m values present in the geometry will be discarded. If the geometry is a curved polygon type (such as a CurvePolygon), it will be automatically segmentized.

Warning
If the geometry is not a single-polygon (or single-curve polygon) type, an empty list will be returned.

Definition at line 2073 of file qgsgeometry.cpp.

◆ asPolyline()

QgsPolylineXY QgsGeometry::asPolyline ( ) const

Returns the contents of the geometry as a polyline.

Any z or m values present in the geometry will be discarded. If the geometry is a curved line type (such as a CircularString), it will be automatically segmentized.

Warning
If the geometry is not a single-line (or single-curve) type, an empty list will be returned.

Definition at line 2027 of file qgsgeometry.cpp.

◆ asQPointF()

QPointF QgsGeometry::asQPointF ( ) const

Returns contents of the geometry as a QPointF if wkbType is WKBPoint, otherwise returns a null QPointF.

Definition at line 3218 of file qgsgeometry.cpp.

◆ asQPolygonF()

QPolygonF QgsGeometry::asQPolygonF ( ) const

Returns contents of the geometry as a QPolygonF.

If geometry is a linestring, then the result will be an open QPolygonF. If the geometry is a polygon, then the result will be a closed QPolygonF of the geometry's exterior ring.

If the geometry is a multi-part geometry, then only the first part will be considered when converting to a QPolygonF.

Definition at line 3224 of file qgsgeometry.cpp.

◆ asWkb()

QByteArray QgsGeometry::asWkb ( QgsAbstractGeometry::WkbFlags  flags = QgsAbstractGeometry::WkbFlags()) const

Export the geometry to WKB.

The optional flags argument specifies flags controlling WKB export behavior (since QGIS 3.14).

Definition at line 3187 of file qgsgeometry.cpp.

◆ asWkt()

QString QgsGeometry::asWkt ( int  precision = 17) const

Exports the geometry to WKT.

Returns
true in case of success and false else
Note
precision parameter added in QGIS 2.4

Definition at line 1674 of file qgsgeometry.cpp.

◆ avoidIntersections()

int QgsGeometry::avoidIntersections ( const QList< QgsVectorLayer * > &  avoidIntersectionsLayers,
const QHash< QgsVectorLayer *, QSet< QgsFeatureId > > &  ignoreFeatures = ( QHash<QgsVectorLayer *, QSet<QgsFeatureId> >() ) 
)

Modifies geometry to avoid intersections with the layers specified in project properties.

Parameters
avoidIntersectionsLayerslist of layers to check for intersections
ignoreFeaturespossibility to give a list of features where intersections should be ignored (not available in Python bindings)
Returns
0 in case of success, 1 if geometry is not of polygon type, 2 if avoid intersection would change the geometry type, 3 at least one geometry intersected is invalid. The algorithm may not work and return the same geometry as the input. You must fix your intersecting geometries. 4 if the geometry is not intersected by one of the geometries present in the provided layers.
Deprecated:
QGIS 3.34

Definition at line 3303 of file qgsgeometry.cpp.

◆ avoidIntersectionsV2()

Qgis::GeometryOperationResult QgsGeometry::avoidIntersectionsV2 ( const QList< QgsVectorLayer * > &  avoidIntersectionsLayers,
const QHash< QgsVectorLayer *, QSet< QgsFeatureId > > &  ignoreFeatures = ( QHash<QgsVectorLayer *, QSet<QgsFeatureId> >() ) 
)

Modifies geometry to avoid intersections with the layers specified in project properties.

Parameters
avoidIntersectionsLayerslist of layers to check for intersections
ignoreFeaturespossibility to give a list of features where intersections should be ignored (not available in Python bindings)
Returns
Success in case of success InvalidInputGeometryType if geometry is not of polygon type GeometryTypeHasChanged if avoid intersection has changed the geometry type InvalidBaseGeometry at least one geometry intersected is invalid. The algorithm may not work and return the same geometry as the input. You must fix your intersecting geometries. NothingHappened if the geometry is not intersected by one of the geometries present in the provided layers.
Since
QGIS 3.34

Definition at line 3274 of file qgsgeometry.cpp.

◆ boundingBox()

QgsRectangle QgsGeometry::boundingBox ( ) const

Returns the bounding box of the geometry.

See also
orientedMinimumBoundingBox()

Definition at line 1317 of file qgsgeometry.cpp.

◆ boundingBox3D()

QgsBox3D QgsGeometry::boundingBox3D ( ) const

Returns the 3D bounding box of the geometry.

Since
QGIS 3.34

Definition at line 1326 of file qgsgeometry.cpp.

◆ boundingBoxIntersects() [1/2]

bool QgsGeometry::boundingBoxIntersects ( const QgsGeometry geometry) const

Returns true if the bounding box of this geometry intersects with the bounding box of another geometry.

Since this test only considers the bounding box of the geometries, is is very fast to calculate and handles invalid geometries.

See also
intersects()

Definition at line 1549 of file qgsgeometry.cpp.

◆ boundingBoxIntersects() [2/2]

bool QgsGeometry::boundingBoxIntersects ( const QgsRectangle rectangle) const

Returns true if the bounding box of this geometry intersects with a rectangle.

Since this test only considers the bounding box of the geometry, is is very fast to calculate and handles invalid geometries.

See also
intersects()

Definition at line 1539 of file qgsgeometry.cpp.

◆ buffer() [1/2]

QgsGeometry QgsGeometry::buffer ( double  distance,
int  segments 
) const

Returns a buffer region around this geometry having the given width and with a specified number of segments used to approximate curves.

See also
singleSidedBuffer()
taperedBuffer()

Definition at line 2399 of file qgsgeometry.cpp.

◆ buffer() [2/2]

QgsGeometry QgsGeometry::buffer ( double  distance,
int  segments,
Qgis::EndCapStyle  endCapStyle,
Qgis::JoinStyle  joinStyle,
double  miterLimit 
) const

Returns a buffer region around the geometry, with additional style options.

Parameters
distancebuffer distance
segmentsfor round joins, number of segments to approximate quarter-circle
endCapStyleend cap style
joinStylejoin style for corners in geometry
miterLimitlimit on the miter ratio used for very sharp corners (JoinStyleMiter only)
See also
singleSidedBuffer()
taperedBuffer()

Definition at line 2418 of file qgsgeometry.cpp.

◆ centroid()

QgsGeometry QgsGeometry::centroid ( ) const

Returns the center of mass of a geometry.

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Note
for line based geometries, the center point of the line is returned, and for point based geometries, the point itself is returned
See also
pointOnSurface()
poleOfInaccessibility()

Definition at line 2633 of file qgsgeometry.cpp.

◆ clipped()

QgsGeometry QgsGeometry::clipped ( const QgsRectangle rectangle)

Clips the geometry using the specified rectangle.

Performs a fast, non-robust intersection between the geometry and a rectangle. The returned geometry may be invalid.

Definition at line 3660 of file qgsgeometry.cpp.

◆ closestSegmentWithContext()

double QgsGeometry::closestSegmentWithContext ( const QgsPointXY point,
QgsPointXY minDistPoint,
int &  nextVertexIndex,
int *  leftOrRightOfSegment = nullptr,
double  epsilon = DEFAULT_SEGMENT_EPSILON 
) const

Searches for the closest segment of geometry to the given point.

Parameters
pointSpecifies the point for search
minDistPointReceives the nearest point on the segment
nextVertexIndexReceives index of the next vertex after the closest segment. The vertex before the closest segment is always nextVertexIndex - 1
leftOrRightOfSegmentOut: Returns if the point is located on the left or right side of the geometry ( < 0 means left, > 0 means right, 0 indicates that the test was unsuccessful, e.g. for a point exactly on the line)
epsilonepsilon for segment snapping
Returns
The squared Cartesian distance is also returned in sqrDist, negative number on error

Definition at line 915 of file qgsgeometry.cpp.

◆ closestVertex()

QgsPointXY QgsGeometry::closestVertex ( const QgsPointXY point,
int &  closestVertexIndex,
int &  previousVertexIndex,
int &  nextVertexIndex,
double &  sqrDist 
) const

Returns the vertex closest to the given point, the corresponding vertex index, squared distance snap point / target point and the indices of the vertices before and after the closest vertex.

Parameters
pointpoint to search for
closestVertexIndexwill be set to the vertex index of the closest found vertex
previousVertexIndexwill be set to the vertex index of the previous vertex from the closest one. Will be set to -1 if not present.
nextVertexIndexwill be set to the vertex index of the next vertex after the closest one. Will be set to -1 if not present.
sqrDistwill be set to the square distance between the closest vertex and the specified point
Returns
closest point in geometry. If not found (empty geometry), returns null point and sqrDist is negative.

Definition at line 531 of file qgsgeometry.cpp.

◆ closestVertexWithContext()

double QgsGeometry::closestVertexWithContext ( const QgsPointXY point,
int &  atVertex 
) const

Searches for the closest vertex in this geometry to the given point.

Parameters
pointSpecifiest the point for search
atVertexReceives index of the closest vertex
Returns
The squared Cartesian distance is also returned in sqrDist, negative number on error

Definition at line 899 of file qgsgeometry.cpp.

◆ coerceToType()

QVector< QgsGeometry > QgsGeometry::coerceToType ( Qgis::WkbType  type,
double  defaultZ = 0,
double  defaultM = 0 
) const

Attempts to coerce this geometry into the specified destination type.

This method will do anything possible to force the current geometry into the specified type. E.g.

  • lines or polygons will be converted to points by return either a single multipoint geometry or multiple single point geometries.
  • polygons will be converted to lines by extracting their exterior and interior rings, returning either a multilinestring or multiple single line strings as dictated by type.
  • lines will be converted to polygon rings if type is a polygon type
  • curved geometries will be segmented if type is non-curved.
  • multi geometries will be converted to a list of single geometries
  • single geometries will be upgraded to multi geometries
  • z or m values will be added or dropped as required.

Since QGIS 3.24, the parameters defaultZ and defaultM control the dimension value added when promoting geometries to Z, M or ZM versions. By default 0.0 is used for Z and M.

Note
This method is much stricter than convertToType(), as it considers the exact WKB type of geometries instead of the geometry family (point/line/polygon), and tries more exhaustively to coerce geometries to the desired type. It also correctly maintains curves and z/m values wherever appropriate.
Since
QGIS 3.14

Definition at line 1698 of file qgsgeometry.cpp.

◆ collectGeometry()

QgsGeometry QgsGeometry::collectGeometry ( const QVector< QgsGeometry > &  geometries)
static

Creates a new multipart geometry from a list of QgsGeometry objects.

Definition at line 385 of file qgsgeometry.cpp.

◆ combine()

QgsGeometry QgsGeometry::combine ( const QgsGeometry geometry,
const QgsGeometryParameters parameters = QgsGeometryParameters() 
) const

Returns a geometry representing all the points in this geometry and other (a union geometry operation).

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Note
this operation is not called union since its a reserved word in C++.

Since QGIS 3.28 the optional parameters argument can be used to specify parameters which control the union results.

Definition at line 3071 of file qgsgeometry.cpp.

◆ compare() [1/3]

bool QgsGeometry::compare ( const QgsMultiPolygonXY p1,
const QgsMultiPolygonXY p2,
double  epsilon = 4 * std::numeric_limits<double>::epsilon() 
)
static

Compares two multipolygons for equality within a specified tolerance.

Parameters
p1first multipolygon
p2second multipolygon
epsilonmaximum difference for coordinates between the multipolygons
Returns
true if multipolygons have the same number of polygons, the polygons have the same number of rings, and each ring has the same number of points and all points are equal within the specified tolerance

Definition at line 3970 of file qgsgeometry.cpp.

◆ compare() [2/3]

bool QgsGeometry::compare ( const QgsPolygonXY p1,
const QgsPolygonXY p2,
double  epsilon = 4 * std::numeric_limits<double>::epsilon() 
)
static

Compares two polygons for equality within a specified tolerance.

Parameters
p1first polygon
p2second polygon
epsilonmaximum difference for coordinates between the polygons
Returns
true if polygons have the same number of rings, and each ring has the same number of points and all points are equal within the specified tolerance

Definition at line 3956 of file qgsgeometry.cpp.

◆ compare() [3/3]

bool QgsGeometry::compare ( const QgsPolylineXY p1,
const QgsPolylineXY p2,
double  epsilon = 4 * std::numeric_limits<double>::epsilon() 
)
static

Compares two polylines for equality within a specified tolerance.

Parameters
p1first polyline
p2second polyline
epsilonmaximum difference for coordinates between the polylines
Returns
true if polylines have the same number of points and all points are equal within the specified tolerance

Definition at line 3943 of file qgsgeometry.cpp.

◆ concaveHull()

QgsGeometry QgsGeometry::concaveHull ( double  targetPercent,
bool  allowHoles = false 
) const

Returns a possibly concave polygon that contains all the points in the geometry.

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.10 or earlier.
Since
QGIS 3.28

Definition at line 2755 of file qgsgeometry.cpp.

◆ const_parts_begin()

QgsAbstractGeometry::const_part_iterator QgsGeometry::const_parts_begin ( ) const

Returns STL-style const iterator pointing to the first part of the geometry.

This method avoids a detach and is more efficient then parts_begin() for read only iteration.

Since
QGIS 3.6

Definition at line 2368 of file qgsgeometry.cpp.

◆ const_parts_end()

QgsAbstractGeometry::const_part_iterator QgsGeometry::const_parts_end ( ) const

Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.

This method avoids a detach and is more efficient then parts_end() for read only iteration.

Since
QGIS 3.6

Definition at line 2375 of file qgsgeometry.cpp.

◆ constGet()

const QgsAbstractGeometry * QgsGeometry::constGet ( ) const

Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.

This is much faster then calling the non-const get() method.

Note
In QGIS 2.x this method was named geometry().
See also
set()
get()

Definition at line 128 of file qgsgeometry.cpp.

◆ constParts()

QgsGeometryConstPartIterator QgsGeometry::constParts ( ) const

Returns Java-style iterator for traversal of parts of the geometry.

This iterator returns read-only references to parts and cannot be used to modify the parts.

Unlike parts(), this method does not force a detach and is more efficient if read-only iteration only is required.

Example

# print the WKT representation of each part in a multi-point geometry
geometry = QgsGeometry.fromWkt( 'MultiPoint( 0 0, 1 1, 2 2)' )
for part in geometry.constParts():
print(part.asWkt())
# single part geometries only have one part - this loop will iterate once only
geometry = QgsGeometry.fromWkt( 'LineString( 0 0, 10 10 )' )
for part in geometry.constParts():
print(part.asWkt())
# part iteration can also be combined with vertex iteration
geometry = QgsGeometry.fromWkt( 'MultiPolygon((( 0 0, 0 10, 10 10, 10 0, 0 0 ),( 5 5, 5 6, 6 6, 6 5, 5 5)),((20 2, 22 2, 22 4, 20 4, 20 2)))' )
for part in geometry.constParts():
for v in part.vertices():
print(v.x(), v.y())
static Q_INVOKABLE QgsGeometry fromWkt(const QString &wkt)
Creates a new geometry from a WKT string.
See also
parts()
vertices()
Since
QGIS 3.6

Definition at line 2391 of file qgsgeometry.cpp.

◆ constrainedDelaunayTriangulation()

QgsGeometry QgsGeometry::constrainedDelaunayTriangulation ( ) const

Returns a constrained Delaunay triangulation for the vertices of the geometry.

An empty geometry will be returned if the triangulation could not be calculated.

This method requires a QGIS build based on GEOS 3.11 or later.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.10 or earlier.
See also
delaunayTriangulation()
Since
QGIS 3.36

Definition at line 2801 of file qgsgeometry.cpp.

◆ contains() [1/3]

bool QgsGeometry::contains ( const QgsGeometry geometry) const

Returns true if the geometry completely contains another geometry.

Note
For performance critical code, or when testing for contains against many different geometries, consider using QgsGeometryEngine instead. This approach can be many orders of magnitude faster than calling contains() directly. See createGeometryEngine() for details on how to use the QgsGeometryEngine class.

Definition at line 1583 of file qgsgeometry.cpp.

◆ contains() [2/3]

bool QgsGeometry::contains ( const QgsPointXY p) const

Returns true if the geometry contains the point p.

Definition at line 1559 of file qgsgeometry.cpp.

◆ contains() [3/3]

bool QgsGeometry::contains ( double  x,
double  y 
) const

Returns true if the geometry contains the point at (x, y).

Since
QGIS 3.38

Definition at line 1571 of file qgsgeometry.cpp.

◆ convertGeometryCollectionToSubclass()

bool QgsGeometry::convertGeometryCollectionToSubclass ( Qgis::GeometryType  geomType)

Converts geometry collection to a the desired geometry type subclass (multi-point, multi-linestring or multi-polygon).

Child geometries of different type are filtered out. Does nothing the geometry is not a geometry collection. May leave the geometry empty if none of the child geometries match the desired type.

Returns
true in case of success and false else
Since
QGIS 3.2

Definition at line 1974 of file qgsgeometry.cpp.

◆ convertPointList() [1/2]

void QgsGeometry::convertPointList ( const QgsPointSequence input,
QVector< QgsPointXY > &  output 
)
static

Downgrades a point list from QgsPoint to QgsPointXY.

Parameters
inputlist of QgsPoint objects to be downgraded
outputdestination for list of points converted to QgsPointXY

Definition at line 3841 of file qgsgeometry.cpp.

◆ convertPointList() [2/2]

void QgsGeometry::convertPointList ( const QVector< QgsPointXY > &  input,
QgsPointSequence output 
)
static

Upgrades a point list from QgsPointXY to QgsPoint.

Parameters
inputlist of QgsPointXY objects to be upgraded
outputdestination for list of points converted to QgsPoint

Definition at line 3832 of file qgsgeometry.cpp.

◆ convertToCurvedMultiType()

bool QgsGeometry::convertToCurvedMultiType ( )

Converts a geometry into a multitype geometry of curve kind (when there is a corresponding curve type).

e.g. a polygon into a multisurface geometry with one polygon, a multipolygon into a multisurface, a linestring into a multicurve geometry with one linestring, or a multilinestring into a multicurve. If it is already a multipart curve geometry, it will return true and not change the geometry. It will also return true and do nothing if the current geometry is a multipoint or a geometry collection. A single point will be transformed to a multipoint.

Returns
true in case of success and false else
Since
QGIS 3.30

Definition at line 1906 of file qgsgeometry.cpp.

◆ convertToCurves()

QgsGeometry QgsGeometry::convertToCurves ( double  distanceTolerance = 1e-8,
double  angleTolerance = 1e-8 
) const

Attempts to convert a non-curved geometry into a curved geometry type (e.g.

LineString to CompoundCurve, Polygon to CurvePolygon).

The distanceTolerance specifies the maximum deviation allowed between the original location of vertices and where they would fall on the candidate curved geometry.

This method only consider a segments as suitable for replacing with an arc if the points are all regularly spaced on the candidate arc. The pointSpacingAngleTolerance parameter specifies the maximum angular deviation (in radians) allowed when testing for regular point spacing.

Note
The API is considered EXPERIMENTAL and can be changed without a notice
Since
QGIS 3.14

Definition at line 2626 of file qgsgeometry.cpp.

◆ convertToMultiType()

bool QgsGeometry::convertToMultiType ( )

Converts single type geometry into multitype geometry e.g.

a polygon into a multipolygon geometry with one polygon If it is already a multipart geometry, it will return true and not change the geometry.

Returns
true in case of success and false else

Definition at line 1874 of file qgsgeometry.cpp.

◆ convertToSingleType()

bool QgsGeometry::convertToSingleType ( )

Converts multi type geometry into single type geometry e.g.

a multipolygon into a polygon geometry. Only the first part of the multi geometry will be retained. If it is already a single part geometry, it will return true and not change the geometry.

Returns
true in case of success and false else

Definition at line 1952 of file qgsgeometry.cpp.

◆ convertToStraightSegment()

void QgsGeometry::convertToStraightSegment ( double  tolerance = M_PI / 180.,
QgsAbstractGeometry::SegmentationToleranceType  toleranceType = QgsAbstractGeometry::MaximumAngle 
)

Converts the geometry to straight line segments, if it is a curved geometry type.

Parameters
tolerancesegmentation tolerance
toleranceTypemaximum segmentation angle or maximum difference between approximation and curve
See also
requiresConversionToStraightSegments

Definition at line 3606 of file qgsgeometry.cpp.

◆ convertToType()

QgsGeometry QgsGeometry::convertToType ( Qgis::GeometryType  destType,
bool  destMultipart = false 
) const

Try to convert the geometry to the requested type.

Parameters
destTypethe geometry type to be converted to
destMultipartdetermines if the output geometry will be multipart or not
Returns
the converted geometry or nullptr if the conversion fails.
Note
The coerceToType() method applies much stricter and more exhaustive attempts to convert between geometry types, and is recommended instead of this method. This method force drops curves and any z or m values present in the geometry.

Definition at line 1856 of file qgsgeometry.cpp.

◆ convexHull()

QgsGeometry QgsGeometry::convexHull ( ) const

Returns the smallest convex polygon that contains all the points in the geometry.

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Definition at line 2737 of file qgsgeometry.cpp.

◆ createGeometryEngine()

QgsGeometryEngine * QgsGeometry::createGeometryEngine ( const QgsAbstractGeometry geometry,
double  precision = 0.0,
Qgis::GeosCreationFlags  flags = Qgis::GeosCreationFlag::SkipEmptyInteriorRings 
)
static

Creates and returns a new geometry engine representing the specified geometry using precision on a grid.

The precision argument was added in 3.36.

A geometry engine is a low-level representation of a QgsAbstractGeometry object, optimised for use with external geometry libraries such as GEOS.

QgsGeometryEngine objects provide a mechanism for optimized evaluation of geometric algorithms, including spatial relationships between geometries and operations such as buffers or clipping. QgsGeometryEngine is recommended for use in any performance critical code instead of directly using the equivalent QgsGeometry methods such as QgsGeometry::intersects().

Many methods available in the QgsGeometryEngine class can benefit from pre-preparing geometries. For instance, whenever a large number of spatial relationships will be tested (such as calling intersects(), within(), etc) then the geometry should first be prepared by calling prepareGeometry() before performing the tests.

The flags argument was added in QGIS 3.40 to allow control over the resultant GEOS geometry.

Example

# polygon_geometry contains a complex polygon, with many vertices
polygon_geometry = QgsGeometry.fromWkt('Polygon((...))')
# create a QgsGeometryEngine representation of the polygon
polygon_geometry_engine = QgsGeometry.createGeometryEngine(polygon_geometry.constGet())
# since we'll be performing many intersects tests, we can speed up these tests considerably
# by first "preparing" the geometry engine
polygon_geometry_engine.prepareGeometry()
# now we are ready to quickly test intersection against many other objects
for feature in my_layer.getFeatures():
feature_geometry = feature.geometry()
# test whether the feature's geometry intersects our original complex polygon
if polygon_geometry_engine.intersects(feature_geometry.constGet()):
print('feature intersects the polygon!')
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...

QgsGeometryEngine operations are backed by the GEOS library (https://trac.osgeo.org/geos/).

Definition at line 4471 of file qgsgeometry.cpp.

◆ createPolygonFromQPolygonF()

QgsPolygonXY QgsGeometry::createPolygonFromQPolygonF ( const QPolygonF &  polygon)
static

Creates a QgsPolygonXYfrom a QPolygonF.

Parameters
polygonsource polygon
Returns
QgsPolygon
See also
createPolylineFromQPolygonF
Deprecated:
QGIS 3.40. Use QgsGeometry::fromQPolygonF() or QgsLineString::fromQPolygonF() instead.

Definition at line 3923 of file qgsgeometry.cpp.

◆ createPolylineFromQPolygonF()

QgsPolylineXY QgsGeometry::createPolylineFromQPolygonF ( const QPolygonF &  polygon)
static

Creates a QgsPolylineXY from a QPolygonF.

Parameters
polygonsource polygon
Returns
QgsPolylineXY
See also
createPolygonFromQPolygonF
Deprecated:
QGIS 3.40. Use QgsGeometry::fromQPolygonF() or QgsLineString::fromQPolygonF() instead.

Definition at line 3932 of file qgsgeometry.cpp.

◆ createWedgeBuffer()

QgsGeometry QgsGeometry::createWedgeBuffer ( const QgsPoint center,
double  azimuth,
double  angularWidth,
double  outerRadius,
double  innerRadius = 0 
)
static

Creates a wedge shaped buffer from a center point.

The azimuth gives the angle (in degrees) for the middle of the wedge to point. The buffer width (in degrees) is specified by the angularWidth parameter. Note that the wedge will extend to half of the angularWidth either side of the azimuth direction.

The outer radius of the buffer is specified via outerRadius, and optionally an innerRadius can also be specified.

The returned geometry will be a CurvePolygon geometry containing circular strings. It may need to be segmentized to convert to a standard Polygon geometry.

Since
QGIS 3.2

Definition at line 414 of file qgsgeometry.cpp.

◆ createWedgeBufferFromAngles()

QgsGeometry QgsGeometry::createWedgeBufferFromAngles ( const QgsPoint center,
double  startAngle,
double  endAngle,
double  outerRadius,
double  innerRadius = 0 
)
static

Creates a wedge shaped buffer from a center point.

The wedges goes from the startAngle to endAngle in degrees.

The outer radius of the buffer is specified via outerRadius, and optionally an innerRadius can also be specified.

The returned geometry will be a CurvePolygon geometry containing circular strings. It may need to be segmentized to convert to a standard Polygon geometry.

Since
QGIS 3.40

Definition at line 422 of file qgsgeometry.cpp.

◆ crosses()

bool QgsGeometry::crosses ( const QgsGeometry geometry) const

Returns true if the geometry crosses another geometry.

Note
For performance critical code, or when testing for crosses against many different geometries, consider using QgsGeometryEngine instead. This approach can be many orders of magnitude faster than calling crosses() directly. See createGeometryEngine() for details on how to use the QgsGeometryEngine class.

Definition at line 1662 of file qgsgeometry.cpp.

◆ delaunayTriangulation()

QgsGeometry QgsGeometry::delaunayTriangulation ( double  tolerance = 0.0,
bool  edgesOnly = false 
) const

Returns the Delaunay triangulation for the vertices of the geometry.

The tolerance parameter specifies an optional snapping tolerance which can be used to improve the robustness of the triangulation. If edgesOnly is true than line string boundary geometries will be returned instead of polygons. An empty geometry will be returned if the diagram could not be calculated.

See also
constrainedDelaunayTriangulation()

Definition at line 2787 of file qgsgeometry.cpp.

◆ deletePart()

bool QgsGeometry::deletePart ( int  partNum)

Deletes part identified by the part number.

Returns
true on success

Definition at line 3256 of file qgsgeometry.cpp.

◆ deleteRing()

bool QgsGeometry::deleteRing ( int  ringNum,
int  partNum = 0 
)

Deletes a ring in polygon or multipolygon.

Ring 0 is outer ring and can't be deleted.

Returns
true on success

Definition at line 3244 of file qgsgeometry.cpp.

◆ deleteVertex()

bool QgsGeometry::deleteVertex ( int  atVertex)

Deletes the vertex at the given position number and item (first number is index 0)

Returns
false if atVertex does not correspond to a valid vertex on this geometry (including if this geometry is a Point), or if the number of remaining vertices in the linestring would be less than two. It is up to the caller to distinguish between these error conditions. (Or maybe we add another method to this object to help make the distinction?)

Definition at line 648 of file qgsgeometry.cpp.

◆ densifyByCount()

QgsGeometry QgsGeometry::densifyByCount ( int  extraNodesPerSegment) const

Returns a copy of the geometry which has been densified by adding the specified number of extra nodes within each segment of the geometry.

If the geometry has z or m values present then these will be linearly interpolated at the added nodes. Curved geometry types are automatically segmentized by this routine.

See also
densifyByDistance()

Definition at line 2612 of file qgsgeometry.cpp.

◆ densifyByDistance()

QgsGeometry QgsGeometry::densifyByDistance ( double  distance) const

Densifies the geometry by adding regularly placed extra nodes inside each segment so that the maximum distance between any two nodes does not exceed the specified distance.

E.g. specifying a distance 3 would cause the segment [0 0] -> [10 0] to be converted to [0 0] -> [2.5 0] -> [5 0] -> [7.5 0] -> [10 0], since 3 extra nodes are required on the segment and spacing these at 2.5 increments allows them to be evenly spaced over the segment. If the geometry has z or m values present then these will be linearly interpolated at the added nodes. Curved geometry types are automatically segmentized by this routine.

See also
densifyByCount()

Definition at line 2619 of file qgsgeometry.cpp.

◆ difference()

QgsGeometry QgsGeometry::difference ( const QgsGeometry geometry,
const QgsGeometryParameters parameters = QgsGeometryParameters() 
) const

Returns a geometry representing the points making up this geometry that do not make up other.

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Since QGIS 3.28 the optional parameters argument can be used to specify parameters which control the difference results.

Definition at line 3110 of file qgsgeometry.cpp.

◆ disjoint()

bool QgsGeometry::disjoint ( const QgsGeometry geometry) const

Returns true if the geometry is disjoint of another geometry.

Note
For performance critical code, or when testing for disjoint against many different geometries, consider using QgsGeometryEngine instead. This approach can be many orders of magnitude faster than calling disjoint() directly. See createGeometryEngine() for details on how to use the QgsGeometryEngine class.

Definition at line 1595 of file qgsgeometry.cpp.

◆ distance()

double QgsGeometry::distance ( const QgsGeometry geom) const

Returns the minimum distance between this geometry and another geometry.

Will return a negative value if either geometry is empty or null.

Warning
QgsGeometry objects are inherently Cartesian/planar geometries, and the distance returned by this method is calculated using strictly Cartesian mathematics.

Definition at line 2264 of file qgsgeometry.cpp.

◆ distanceToVertex()

double QgsGeometry::distanceToVertex ( int  vertex) const

Returns the distance along this geometry from its first vertex to the specified vertex.

Parameters
vertexvertex index to calculate distance to
Returns
distance to vertex (following geometry), or -1 for invalid vertex numbers
Warning
QgsGeometry objects are inherently Cartesian/planar geometries, and the distance returned by this method is calculated using strictly Cartesian mathematics.

Definition at line 559 of file qgsgeometry.cpp.

◆ draw()

void QgsGeometry::draw ( QPainter &  p) const

Draws the geometry onto a QPainter.

Parameters
pdestination QPainter

Definition at line 3679 of file qgsgeometry.cpp.

◆ equals()

bool QgsGeometry::equals ( const QgsGeometry geometry) const

Test if this geometry is exactly equal to another geometry.

This is a strict equality check, where the underlying geometries must have exactly the same type, component vertices and vertex order.

Calling this method is dramatically faster than the topological equality test performed by isGeosEqual().

Note
Comparing two null geometries will return false.
See also
isGeosEqual()

Definition at line 1607 of file qgsgeometry.cpp.

◆ extendLine()

QgsGeometry QgsGeometry::extendLine ( double  startDistance,
double  endDistance 
) const

Extends a (multi)line geometry by extrapolating out the start or end of the line by a specified distance.

Lines are extended using the bearing of the first or last segment in the line.

Definition at line 2553 of file qgsgeometry.cpp.

◆ extrude()

QgsGeometry QgsGeometry::extrude ( double  x,
double  y 
)

Returns an extruded version of this geometry.

Definition at line 3150 of file qgsgeometry.cpp.

◆ filterVertices()

void QgsGeometry::filterVertices ( const std::function< bool(const QgsPoint &) > &  filter)

Filters the vertices from the geometry in place, removing any which do not return true for the filter function check.

Has no effect when called on a single point geometry.

Depending on the filter used, this may result in an invalid geometry.

Note
Not available in Python bindings
Since
QGIS 3.2

Definition at line 3812 of file qgsgeometry.cpp.

◆ forcePolygonClockwise()

QgsGeometry QgsGeometry::forcePolygonClockwise ( ) const

Forces geometries to respect the exterior ring is clockwise, interior rings are counter-clockwise convention.

This convention is used primarily by ESRI software.

See also
isPolygonClockwise()
isPolygonCounterClockwise()
forcePolygonCounterClockwise()
Since
QGIS 3.24

Definition at line 3382 of file qgsgeometry.cpp.

◆ forcePolygonCounterClockwise()

QgsGeometry QgsGeometry::forcePolygonCounterClockwise ( ) const

Forces geometries to respect the exterior ring is counter-clockwise, interior rings are clockwise convention.

This convention matches the OGC Simple Features specification.

See also
isPolygonClockwise()
isPolygonCounterClockwise()
forcePolygonClockwise()
Since
QGIS 3.24

Definition at line 3424 of file qgsgeometry.cpp.

◆ forceRHR()

QgsGeometry QgsGeometry::forceRHR ( ) const

Forces geometries to respect the Right-Hand-Rule, in which the area that is bounded by a polygon is to the right of the boundary.

In particular, the exterior ring is oriented in a clockwise direction and the interior rings in a counter-clockwise direction.

Warning
Due to the conflicting definitions of the right-hand-rule in general use, it is recommended to use the explicit forcePolygonClockwise() or forcePolygonCounterClockwise() methods instead.
See also
isPolygonClockwise()
isPolygonCounterClockwise()
forcePolygonClockwise()
forcePolygonCounterClockwise()
Since
QGIS 3.6

Definition at line 3349 of file qgsgeometry.cpp.

◆ frechetDistance()

double QgsGeometry::frechetDistance ( const QgsGeometry geom) const

Returns the Fréchet distance between this geometry and geom, restricted to discrete points for both geometries.

The Fréchet distance is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. Therefore it is often better than the Hausdorff distance.

In case of error -1 will be returned.

This method requires a QGIS build based on GEOS 3.7 or later.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.6 or earlier.
See also
frechetDistanceDensify()
Since
QGIS 3.20

Definition at line 2307 of file qgsgeometry.cpp.

◆ frechetDistanceDensify()

double QgsGeometry::frechetDistanceDensify ( const QgsGeometry geom,
double  densifyFraction 
) const

Returns the Fréchet distance between this geometry and geom, restricted to discrete points for both geometries.

The Fréchet distance is a measure of similarity between curves that takes into account the location and ordering of the points along the curves. Therefore it is often better than the Hausdorff distance.

This function accepts a densifyFraction argument. The function performs a segment densification before computing the discrete Fréchet distance. The densifyFraction parameter sets the fraction by which to densify each segment. Each segment will be split into a number of equal-length subsegments, whose fraction of the total length is closest to the given fraction.

This method can be used when the default approximation provided by frechetDistance() is not sufficient. Decreasing the densifyFraction parameter will make the distance returned approach the true Fréchet distance for the geometries.

This method requires a QGIS build based on GEOS 3.7 or later.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.6 or earlier.
See also
frechetDistance()
Since
QGIS 3.20

Definition at line 2319 of file qgsgeometry.cpp.

◆ fromBox3D()

QgsGeometry QgsGeometry::fromBox3D ( const QgsBox3D box)
static

Creates a new geometry from a QgsBox3D object Returns a 2D polygon geometry if the box is purely 2d, otherwise returns a polyhedral surface geometry.

Since
QGIS 3.34

Definition at line 259 of file qgsgeometry.cpp.

◆ fromMultiPointXY()

QgsGeometry QgsGeometry::fromMultiPointXY ( const QgsMultiPointXY multipoint)
static

Creates a new geometry from a QgsMultiPointXY object.

Definition at line 208 of file qgsgeometry.cpp.

◆ fromMultiPolygonXY()

QgsGeometry QgsGeometry::fromMultiPolygonXY ( const QgsMultiPolygonXY multipoly)
static

Creates a new geometry from a QgsMultiPolygonXY.

Definition at line 228 of file qgsgeometry.cpp.

◆ fromMultiPolylineXY()

QgsGeometry QgsGeometry::fromMultiPolylineXY ( const QgsMultiPolylineXY multiline)
static

Creates a new geometry from a QgsMultiPolylineXY object.

Definition at line 218 of file qgsgeometry.cpp.

◆ fromPoint()

QgsGeometry QgsGeometry::fromPoint ( const QgsPoint point)
static

Creates a new geometry from a QgsPoint object.

Since
QGIS 3.34

Definition at line 178 of file qgsgeometry.cpp.

◆ fromPointXY()

QgsGeometry QgsGeometry::fromPointXY ( const QgsPointXY point)
static

Creates a new geometry from a QgsPointXY object.

Definition at line 168 of file qgsgeometry.cpp.

◆ fromPolygonXY()

QgsGeometry QgsGeometry::fromPolygonXY ( const QgsPolygonXY polygon)
static

Creates a new geometry from a QgsPolygonXY.

Definition at line 198 of file qgsgeometry.cpp.

◆ fromPolyline()

QgsGeometry QgsGeometry::fromPolyline ( const QgsPolyline polyline)
static

Creates a new LineString geometry from a list of QgsPoint points.

This method will respect any Z or M dimensions present in the input points. E.g. if input points are PointZ type, the resultant linestring will be a LineStringZ type.

Definition at line 193 of file qgsgeometry.cpp.

◆ fromPolylineXY()

QgsGeometry QgsGeometry::fromPolylineXY ( const QgsPolylineXY polyline)
static

Creates a new LineString geometry from a list of QgsPointXY points.

Using fromPolyline() is preferred, as fromPolyline() is more efficient and will respect any Z or M dimensions present in the input points.

Note
In QGIS 2.x this method was available as fromPolyline().
See also
fromPolyline()

Definition at line 183 of file qgsgeometry.cpp.

◆ fromQPointF()

QgsGeometry QgsGeometry::fromQPointF ( QPointF  point)
static

Construct geometry from a QPointF.

Parameters
pointsource QPointF

Definition at line 3902 of file qgsgeometry.cpp.

◆ fromQPolygonF()

QgsGeometry QgsGeometry::fromQPolygonF ( const QPolygonF &  polygon)
static

Construct geometry from a QPolygonF.

If the polygon is closed than the resultant geometry will be a polygon, if it is open than the geometry will be a polyline.

Parameters
polygonsource QPolygonF

Definition at line 3907 of file qgsgeometry.cpp.

◆ fromRect()

QgsGeometry QgsGeometry::fromRect ( const QgsRectangle rect)
static

Creates a new geometry from a QgsRectangle.

Definition at line 238 of file qgsgeometry.cpp.

◆ fromWkb() [1/2]

void QgsGeometry::fromWkb ( const QByteArray &  wkb)

Set the geometry, feeding in the buffer containing OGC Well-Known Binary.

Definition at line 486 of file qgsgeometry.cpp.

◆ fromWkb() [2/2]

void QgsGeometry::fromWkb ( unsigned char *  wkb,
int  length 
)

Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length.

This class will take ownership of the buffer.

Note
not available in Python bindings

Definition at line 479 of file qgsgeometry.cpp.

◆ fromWkt()

QgsGeometry QgsGeometry::fromWkt ( const QString &  wkt)
static

Creates a new geometry from a WKT string.

Definition at line 158 of file qgsgeometry.cpp.

◆ get()

QgsAbstractGeometry * QgsGeometry::get ( )

Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.

This method can be slow to call, as it may trigger a detachment of the geometry and a deep copy. Where possible, use constGet() instead.

Note
In QGIS 2.x this method was named geometry().
See also
constGet()
set()

Definition at line 133 of file qgsgeometry.cpp.

◆ hausdorffDistance()

double QgsGeometry::hausdorffDistance ( const QgsGeometry geom) const

Returns the Hausdorff distance between this geometry and geom.

This is basically a measure of how similar or dissimilar 2 geometries are.

This algorithm is an approximation to the standard Hausdorff distance. This approximation is exact or close enough for a large subset of useful cases. Examples of these are:

  • computing distance between Linestrings that are roughly parallel to each other, and roughly equal in length. This occurs in matching linear networks.
  • Testing similarity of geometries.

If the default approximate provided by this method is insufficient, use hausdorffDistanceDensify() instead.

In case of error -1 will be returned.

See also
hausdorffDistanceDensify()

Definition at line 2282 of file qgsgeometry.cpp.

◆ hausdorffDistanceDensify()

double QgsGeometry::hausdorffDistanceDensify ( const QgsGeometry geom,
double  densifyFraction 
) const

Returns the Hausdorff distance between this geometry and geom.

This is basically a measure of how similar or dissimilar 2 geometries are.

This function accepts a densifyFraction argument. The function performs a segment densification before computing the discrete Hausdorff distance. The densifyFraction parameter sets the fraction by which to densify each segment. Each segment will be split into a number of equal-length subsegments, whose fraction of the total length is closest to the given fraction.

This method can be used when the default approximation provided by hausdorffDistance() is not sufficient. Decreasing the densifyFraction parameter will make the distance returned approach the true Hausdorff distance for the geometries.

In case of error -1 will be returned.

See also
hausdorffDistance()

Definition at line 2294 of file qgsgeometry.cpp.

◆ insertVertex() [1/2]

bool QgsGeometry::insertVertex ( const QgsPoint point,
int  beforeVertex 
)

Insert a new vertex before the given vertex index, ring and item (first number is index 0) If the requested vertex number (beforeVertex.back()) is greater than the last actual vertex on the requested ring and item, it is assumed that the vertex is to be appended instead of inserted.

Returns false if atVertex does not correspond to a valid vertex on this geometry (including if this geometry is a Point). It is up to the caller to distinguish between these error conditions. (Or maybe we add another method to this object to help make the distinction?)

Definition at line 790 of file qgsgeometry.cpp.

◆ insertVertex() [2/2]

bool QgsGeometry::insertVertex ( double  x,
double  y,
int  beforeVertex 
)

Insert a new vertex before the given vertex index, ring and item (first number is index 0) If the requested vertex number (beforeVertex.back()) is greater than the last actual vertex on the requested ring and item, it is assumed that the vertex is to be appended instead of inserted.

Returns false if atVertex does not correspond to a valid vertex on this geometry (including if this geometry is a Point). It is up to the caller to distinguish between these error conditions. (Or maybe we add another method to this object to help make the distinction?)

Definition at line 764 of file qgsgeometry.cpp.

◆ interpolate()

QgsGeometry QgsGeometry::interpolate ( double  distance) const

Returns an interpolated point on the geometry at the specified distance.

If the original geometry is a polygon type, the boundary of the polygon will be used during interpolation. If the original geometry is a point type, a null geometry will be returned.

If z or m values are present, the output z and m will be interpolated using the existing vertices' z or m values.

If the input is a NULL geometry, the output will also be a NULL geometry.

See also
lineLocatePoint()

Definition at line 2922 of file qgsgeometry.cpp.

◆ interpolateAngle()

double QgsGeometry::interpolateAngle ( double  distance) const

Returns the angle parallel to the linestring or polygon boundary at the specified distance along the geometry.

Angles are in radians, clockwise from north. If the distance coincides precisely at a node then the average angle from the segment either side of the node is returned.

Parameters
distancedistance along geometry
See also
angleAtVertex()

Definition at line 2991 of file qgsgeometry.cpp.

◆ intersection()

QgsGeometry QgsGeometry::intersection ( const QgsGeometry geometry,
const QgsGeometryParameters parameters = QgsGeometryParameters() 
) const

Returns a geometry representing the points shared by this geometry and other.

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Since QGIS 3.28 the optional parameters argument can be used to specify parameters which control the intersection results.

Definition at line 3049 of file qgsgeometry.cpp.

◆ intersects() [1/2]

bool QgsGeometry::intersects ( const QgsGeometry geometry) const

Returns true if this geometry exactly intersects with another geometry.

This test is exact and can be slow for complex geometries.

The GEOS library is used to perform the intersection test. Geometries which are not valid may return incorrect results.

Note
For performance critical code, or when testing for intersection against many different geometries, consider using QgsGeometryEngine instead. This approach can be many orders of magnitude faster than calling intersects() directly. See createGeometryEngine() for details on how to use the QgsGeometryEngine class.
See also
boundingBoxIntersects()

Definition at line 1527 of file qgsgeometry.cpp.

◆ intersects() [2/2]

bool QgsGeometry::intersects ( const QgsRectangle rectangle) const

Returns true if this geometry exactly intersects with a rectangle.

This test is exact and can be slow for complex geometries.

The GEOS library is used to perform the intersection test. Geometries which are not valid may return incorrect results.

See also
boundingBoxIntersects()

Definition at line 1502 of file qgsgeometry.cpp.

◆ isAxisParallelRectangle()

bool QgsGeometry::isAxisParallelRectangle ( double  maximumDeviation,
bool  simpleRectanglesOnly = false 
) const

Returns true if the geometry is a polygon that is almost an axis-parallel rectangle.

The maximumDeviation argument specifes the maximum angle (in degrees) that the polygon edges are allowed to deviate from axis parallel lines.

By default the check will permit polygons with more than 4 edges, so long as the overall shape of the polygon is an axis-parallel rectangle (i.e. it is tolerant to rectangles with additional vertices added along the rectangle sides). If simpleRectanglesOnly is set to true then the method will only return true if the geometry is a simple rectangle consisting of 4 edges.

Since
QGIS 3.20

Definition at line 3538 of file qgsgeometry.cpp.

◆ isEmpty()

bool QgsGeometry::isEmpty ( ) const

Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geometries).

A null geometry will always return true for isEmpty().

See also
isNull()

Definition at line 513 of file qgsgeometry.cpp.

◆ isGeosEqual()

bool QgsGeometry::isGeosEqual ( const QgsGeometry g) const

Compares the geometry with another geometry using GEOS.

This method performs a slow, topological check, where geometries are considered equal if all of the their component edges overlap. E.g. lines with the same vertex locations but opposite direction will be considered equal by this method.

Consider using the much faster, stricter equality test performed by equals() instead.

Note
Comparing two null geometries will return false.
See also
equals()

Definition at line 3547 of file qgsgeometry.cpp.

◆ isGeosValid()

bool QgsGeometry::isGeosValid ( Qgis::GeometryValidityFlags  flags = Qgis::GeometryValidityFlags()) const

Checks validity of the geometry using GEOS.

The flags parameter indicates optional flags which control the type of validity checking performed.

Definition at line 3518 of file qgsgeometry.cpp.

◆ isMultipart()

bool QgsGeometry::isMultipart ( ) const

Returns true if WKB of the geometry is of WKBMulti* type.

Definition at line 523 of file qgsgeometry.cpp.

◆ isNull()

bool QgsGeometry::isNull ( ) const

Returns true if the geometry is null (ie, contains no underlying geometry accessible via get() or constGet() ).

See also
get
constGet()
isEmpty()

Definition at line 149 of file qgsgeometry.cpp.

◆ isPolygonClockwise()

bool QgsGeometry::isPolygonClockwise ( ) const
inline

Returns True if the Polygon is clockwise.

Warning
Only the first exterior ring is taken to perform this operation. In case of degenerate orders, you have to perform in deep verification.
returns true if the geometry is not a polygon type or empty
See also
isPolygonCounterClockwise()
forcePolygonClockwise()
forcePolygonCounterClockwise()
Since
QGIS 3.36

Definition at line 2700 of file qgsgeometry.h.

◆ isPolygonCounterClockwise()

bool QgsGeometry::isPolygonCounterClockwise ( ) const
inline

Returns True if the Polygon is counter-clockwise.

Warning
Only the first exterior ring is taken to perform this operation. In case of degenerate orders, you have to perform in deep verification.
returns false if the geometry is not a polygon type or empty
See also
isPolygonClockwise()
forcePolygonClockwise()
forcePolygonCounterClockwise()
Since
QGIS 3.36

Definition at line 2685 of file qgsgeometry.h.

◆ isSimple()

bool QgsGeometry::isSimple ( ) const

Determines whether the geometry is simple (according to OGC definition), i.e.

it has no anomalous geometric points, such as self-intersection or self-tangency. Uses GEOS library for the test.

Note
This is useful mainly for linestrings and linear rings. Polygons are simple by definition, for checking anomalies in polygon geometries one can use isGeosValid().

Definition at line 3528 of file qgsgeometry.cpp.

◆ largestEmptyCircle()

QgsGeometry QgsGeometry::largestEmptyCircle ( double  tolerance,
const QgsGeometry boundary = QgsGeometry() 
) const

Constructs the Largest Empty Circle for a set of obstacle geometries, up to a specified tolerance.

The Largest Empty Circle is the largest circle which has its center in the convex hull of the obstacles (the boundary), and whose interior does not intersect with any obstacle. The circle center is the point in the interior of the boundary which has the farthest distance from the obstacles (up to tolerance). The circle is determined by the center point and a point lying on an obstacle indicating the circle radius. The implementation uses a successive-approximation technique over a grid of square cells covering the obstacles and boundary. The grid is refined using a branch-and-bound algorithm. Point containment and distance are computed in a performant way by using spatial indexes. Returns a two-point linestring, with one point at the center of the inscribed circle and the other on the boundary of the inscribed circle.

This method requires QGIS builds based on GEOS 3.9 or later.

Warning
the tolerance value must be a value greater than 0, or the algorithm may never converge on a solution
Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.8 or earlier.
Since
QGIS 3.20

Definition at line 2679 of file qgsgeometry.cpp.

◆ lastError()

QString QgsGeometry::lastError ( ) const

Returns an error string referring to the last error encountered either when this geometry was created or when an operation was performed on the geometry.

Definition at line 3807 of file qgsgeometry.cpp.

◆ length()

double QgsGeometry::length ( ) const

Returns the planar, 2-dimensional length of geometry.

If the geometry is a polygon geometry then the perimeter of the polygon will be returned.

Warning
QgsGeometry objects are inherently Cartesian/planar geometries, and the length returned by this method is calculated using strictly Cartesian mathematics. In contrast, the QgsDistanceArea class exposes methods for calculating the lengths of geometries using geodesic calculations which account for the curvature of the Earth (or any other celestial body).
See also
area()

Definition at line 2239 of file qgsgeometry.cpp.

◆ lineLocatePoint()

double QgsGeometry::lineLocatePoint ( const QgsGeometry point) const

Returns a distance representing the location along this linestring of the closest point on this linestring geometry to the specified point.

Ie, the returned value indicates how far along this linestring you need to traverse to get to the closest location where this linestring comes to the specified point.

Parameters
pointpoint to seek proximity to
Returns
distance along line, or -1 on error
Note
only valid for linestring geometries
See also
interpolate()

Definition at line 2972 of file qgsgeometry.cpp.

◆ makeDifference()

QgsGeometry QgsGeometry::makeDifference ( const QgsGeometry other) const

Returns the geometry formed by modifying this geometry such that it does not intersect the other geometry.

Parameters
othergeometry that should not be intersect
Returns
difference geometry, or empty geometry if difference could not be calculated

Definition at line 1296 of file qgsgeometry.cpp.

◆ makeDifferenceInPlace()

int QgsGeometry::makeDifferenceInPlace ( const QgsGeometry other)

Changes this geometry such that it does not intersect the other geometry.

Parameters
othergeometry that should not be intersect
Note
Not available in Python

Definition at line 1276 of file qgsgeometry.cpp.

◆ makeValid()

QgsGeometry QgsGeometry::makeValid ( Qgis::MakeValidMethod  method = Qgis::MakeValidMethod::Linework,
bool  keepCollapsed = false 
) const

Attempts to make an invalid geometry valid without losing vertices.

Already-valid geometries are returned without further intervention. In case of full or partial dimensional collapses, the output geometry may be a collection of lower-to-equal dimension geometries or a geometry of lower dimension. Single polygons may become multi-geometries in case of self-intersections. It preserves Z values, but M values will be dropped.

If an error was encountered during the process, more information can be retrieved by calling lastError() on the returned geometry.

The method and keepCollapsed arguments are available since QGIS 3.28. They require builds based on GEOS 3.10 or later.

Returns
new valid QgsGeometry or null geometry on error
Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.9 or earlier when the method is not Qgis::MakeValidMethod::Linework or the keepCollapsed option is set.

Definition at line 3335 of file qgsgeometry.cpp.

◆ mapToPixel()

void QgsGeometry::mapToPixel ( const QgsMapToPixel mtp)

Transforms the geometry from map units to pixels in place.

Parameters
mtpmap to pixel transform

Definition at line 3651 of file qgsgeometry.cpp.

◆ mergeLines()

QgsGeometry QgsGeometry::mergeLines ( ) const

Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line strings.

Returns
a LineString or MultiLineString geometry, with any connected lines joined. An empty geometry will be returned if the input geometry was not a MultiLineString geometry.

Definition at line 3090 of file qgsgeometry.cpp.

◆ minimalEnclosingCircle() [1/2]

QgsGeometry QgsGeometry::minimalEnclosingCircle ( QgsPointXY center,
double &  radius,
unsigned int  segments = 36 
) const

Returns the minimal enclosing circle for the geometry.

Parameters
centerCenter of the minimal enclosing circle returneds
radiusRadius of the minimal enclosing circle returned
segmentsNumber of segments used to segment geometry.
See also
QgsEllipse::toPolygon()
Returns
the minimal enclosing circle as a QGIS geometry

Definition at line 1400 of file qgsgeometry.cpp.

◆ minimalEnclosingCircle() [2/2]

QgsGeometry QgsGeometry::minimalEnclosingCircle ( unsigned int  segments = 36) const

Returns the minimal enclosing circle for the geometry.

Parameters
segmentsNumber of segments used to segment geometry.
See also
QgsEllipse::toPolygon()

Definition at line 1427 of file qgsgeometry.cpp.

◆ minimumClearance()

double QgsGeometry::minimumClearance ( ) const

Computes the minimum clearance of a geometry.

The minimum clearance is the smallest amount by which a vertex could be moved to produce an invalid polygon, a non-simple linestring, or a multipoint with repeated points. If a geometry has a minimum clearance of 'eps', it can be said that:

  • No two distinct vertices in the geometry are separated by less than 'eps'
  • No vertex is closer than 'eps' to a line segment of which it is not an endpoint.

If the minimum clearance cannot be defined for a geometry (such as with a single point, or a multipoint whose points are identical) a value of infinity will be returned.

If an error occurs while calculating the clearance NaN will be returned.

This method requires a QGIS build based on GEOS 3.6 or later.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.5 or earlier.
Since
QGIS 3.20

Definition at line 2709 of file qgsgeometry.cpp.

◆ minimumClearanceLine()

QgsGeometry QgsGeometry::minimumClearanceLine ( ) const

Returns a LineString whose endpoints define the minimum clearance of a geometry.

If the geometry has no minimum clearance, an empty LineString will be returned.

This method requires a QGIS build based on GEOS 3.6 or later.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.5 or earlier.
Since
QGIS 3.20

Definition at line 2722 of file qgsgeometry.cpp.

◆ minimumWidth()

QgsGeometry QgsGeometry::minimumWidth ( ) const

Returns a linestring geometry which represents the minimum diameter of the geometry.

The minimum diameter is defined to be the width of the smallest band that contains the geometry, where a band is a strip of the plane defined by two parallel lines. This can be thought of as the smallest hole that the geometry can be moved through, with a single rotation.

This method requires a QGIS build based on GEOS 3.6 or later.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.5 or earlier.
Since
QGIS 3.20

Definition at line 2694 of file qgsgeometry.cpp.

◆ moveVertex() [1/2]

bool QgsGeometry::moveVertex ( const QgsPoint p,
int  atVertex 
)

Moves the vertex at the given position number and item (first number is index 0) to the given coordinates.

Returns false if atVertex does not correspond to a valid vertex on this geometry

Definition at line 630 of file qgsgeometry.cpp.

◆ moveVertex() [2/2]

bool QgsGeometry::moveVertex ( double  x,
double  y,
int  atVertex 
)

Moves the vertex at the given position number and item (first number is index 0) to the given coordinates.

Returns false if atVertex does not correspond to a valid vertex on this geometry

Definition at line 612 of file qgsgeometry.cpp.

◆ nearestPoint()

QgsGeometry QgsGeometry::nearestPoint ( const QgsGeometry other) const

Returns the nearest (closest) point on this geometry to another geometry.

See also
shortestLine()

Definition at line 869 of file qgsgeometry.cpp.

◆ node()

QgsGeometry QgsGeometry::node ( ) const

Returns a (Multi)LineString representing the fully noded version of a collection of linestrings.

The noding preserves all of the input nodes, and introduces the least possible number of new nodes. The resulting linework is dissolved (duplicate lines are removed).

The input geometry type should be a (Multi)LineString.

Since
QGIS 3.20

Definition at line 2867 of file qgsgeometry.cpp.

◆ normalize()

void QgsGeometry::normalize ( )

Reorganizes the geometry into a normalized form (or "canonical" form).

Polygon rings will be rearranged so that their starting vertex is the lower left and ring orientation follows the right hand rule, collections are ordered by geometry type, and other normalization techniques are applied. The resultant geometry will be geometrically equivalent to the original geometry.

Since
QGIS 3.20

Definition at line 3507 of file qgsgeometry.cpp.

◆ offsetCurve()

QgsGeometry QgsGeometry::offsetCurve ( double  distance,
int  segments,
Qgis::JoinStyle  joinStyle,
double  miterLimit 
) const

Returns an offset line at a given distance and side from an input line.

Parameters
distancebuffer distance
segmentsfor round joins, number of segments to approximate quarter-circle
joinStylejoin style for corners in geometry
miterLimitlimit on the miter ratio used for very sharp corners (JoinStyleMiter only)

Definition at line 2437 of file qgsgeometry.cpp.

◆ operator QVariant()

QgsGeometry::operator QVariant ( ) const
inline

Allows direct construction of QVariants from geometry.

Definition at line 3182 of file qgsgeometry.h.

◆ operator=()

QgsGeometry & QgsGeometry::operator= ( QgsGeometry const &  rhs)

Creates a shallow copy of the geometry.

Note
not available in Python bindings

Definition at line 90 of file qgsgeometry.cpp.

◆ orientedMinimumBoundingBox() [1/2]

QgsGeometry QgsGeometry::orientedMinimumBoundingBox ( ) const

Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated rectangle which fully encompasses the geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Definition at line 1346 of file qgsgeometry.cpp.

◆ orientedMinimumBoundingBox() [2/2]

QgsGeometry QgsGeometry::orientedMinimumBoundingBox ( double &  area,
double &  angle,
double &  width,
double &  height 
) const

Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated rectangle which fully encompasses the geometry.

The area, angle (clockwise in degrees from North), width and height of the rotated bounding box will also be returned.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

See also
boundingBox()

Definition at line 1336 of file qgsgeometry.cpp.

◆ orthogonalize()

QgsGeometry QgsGeometry::orthogonalize ( double  tolerance = 1.0E-8,
int  maxIterations = 1000,
double  angleThreshold = 15.0 
) const

Attempts to orthogonalize a line or polygon geometry by shifting vertices to make the geometries angles either right angles or flat lines.

This is an iterative algorithm which will loop until either the vertices are within a specified tolerance of right angles or a set number of maximum iterations is reached. The angle threshold parameter specifies how close to a right angle or straight line an angle must be before it is attempted to be straightened.

Definition at line 1435 of file qgsgeometry.cpp.

◆ overlaps()

bool QgsGeometry::overlaps ( const QgsGeometry geometry) const

Returns true if the geometry overlaps another geometry.

Note
For performance critical code, or when testing for overlaps against many different geometries, consider using QgsGeometryEngine instead. This approach can be many orders of magnitude faster than calling overlaps() directly. See createGeometryEngine() for details on how to use the QgsGeometryEngine class.

Definition at line 1638 of file qgsgeometry.cpp.

◆ parts()

QgsGeometryPartIterator QgsGeometry::parts ( )

Returns Java-style iterator for traversal of parts of the geometry.

This iterator can safely be used to modify parts of the geometry.

This method forces a detach. Use constParts() to avoid the detach if the parts are not going to be modified.

Example

# print the WKT representation of each part in a multi-point geometry
geometry = QgsGeometry.fromWkt( 'MultiPoint( 0 0, 1 1, 2 2)' )
for part in geometry.parts():
print(part.asWkt())
# single part geometries only have one part - this loop will iterate once only
geometry = QgsGeometry.fromWkt( 'LineString( 0 0, 10 10 )' )
for part in geometry.parts():
print(part.asWkt())
# parts can be modified during the iteration
geometry = QgsGeometry.fromWkt( 'MultiPoint( 0 0, 1 1, 2 2)' )
for part in geometry.parts():
part.transform(ct)
# part iteration can also be combined with vertex iteration
geometry = QgsGeometry.fromWkt( 'MultiPolygon((( 0 0, 0 10, 10 10, 10 0, 0 0 ),( 5 5, 5 6, 6 6, 6 5, 5 5)),((20 2, 22 2, 22 4, 20 4, 20 2)))' )
for part in geometry.parts():
for v in part.vertices():
print(v.x(), v.y())
See also
constParts()
vertices()
Since
QGIS 3.6

Definition at line 2382 of file qgsgeometry.cpp.

◆ parts_begin()

QgsAbstractGeometry::part_iterator QgsGeometry::parts_begin ( )

Returns STL-style iterator pointing to the first part of the geometry.

This method forces a detach. Use const_parts_begin() to avoid the detach if the parts are not going to be modified.

Since
QGIS 3.6

Definition at line 2352 of file qgsgeometry.cpp.

◆ parts_end()

QgsAbstractGeometry::part_iterator QgsGeometry::parts_end ( )

Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.

This method forces a detach. Use const_parts_begin() to avoid the detach if the parts are not going to be modified.

Since
QGIS 3.6

Definition at line 2361 of file qgsgeometry.cpp.

◆ pointOnSurface()

QgsGeometry QgsGeometry::pointOnSurface ( ) const

Returns a point guaranteed to lie on the surface of a geometry.

While the centroid() of a geometry may be located outside of the geometry itself (e.g., for concave shapes), the point on surface will always be inside the geometry.

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

See also
centroid()
poleOfInaccessibility()

Definition at line 2657 of file qgsgeometry.cpp.

◆ poleOfInaccessibility()

QgsGeometry QgsGeometry::poleOfInaccessibility ( double  precision,
double *  distanceToBoundary = nullptr 
) const

Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal point from the boundary of the surface.

This function uses the 'polylabel' algorithm (Vladimir Agafonkin, 2016), which is an iterative approach guaranteed to find the true pole of inaccessibility within a specified tolerance. More precise tolerances require more iterations and will take longer to calculate. Optionally, the distance to the polygon boundary from the pole can be stored.

See also
centroid()
pointOnSurface()

Definition at line 2672 of file qgsgeometry.cpp.

◆ polygonize()

QgsGeometry QgsGeometry::polygonize ( const QVector< QgsGeometry > &  geometries)
static

Creates a GeometryCollection geometry containing possible polygons formed from the constituent linework of a set of geometries.

The input geometries must be fully noded (i.e. nodes exist at every common intersection of the geometries). The easiest way to ensure this is to first call unaryUnion() on the set of input geometries and then pass the result to polygonize(). An empty geometry will be returned in the case of errors.

Definition at line 3589 of file qgsgeometry.cpp.

◆ polygonOrientation()

Qgis::AngularDirection QgsGeometry::polygonOrientation ( ) const

Returns the orientation of the polygon.

Warning
Only the first exterior ring is taken to perform this operation. In case of degenerate orders, you have to perform in deep verification.
returns Qgis::AngularDirection::NoOrientation if the geometry is not a polygon type or empty
Since
QGIS 3.36

Definition at line 3354 of file qgsgeometry.cpp.

◆ randomPointsInPolygon() [1/2]

QVector< QgsPointXY > QgsGeometry::randomPointsInPolygon ( int  count,
const std::function< bool(const QgsPointXY &) > &  acceptPoint,
unsigned long  seed = 0,
QgsFeedback feedback = nullptr,
int  maxTriesPerPoint = 0 
) const

Returns a list of count random points generated inside a (multi)polygon geometry (if acceptPoint is specified, and restrictive, the number of points returned may be less than count).

Optionally, a specific random seed can be used when generating points. If seed is 0, then a completely random sequence of points will be generated.

If the source geometry is not a (multi)polygon, an empty list will be returned.

The optional feedback argument can be used to provide cancellation support during the point generation.

The acceptPoint function is used to filter result candidates. If the function returns false, then the point will not be accepted and another candidate generated.

When acceptPoint is specified, maxTriesPerPoint defines how many attempts to make before giving up generating a point.

Since
QGIS 3.10

◆ randomPointsInPolygon() [2/2]

QVector< QgsPointXY > QgsGeometry::randomPointsInPolygon ( int  count,
unsigned long  seed = 0,
QgsFeedback feedback = nullptr 
) const

Returns a list of count random points generated inside a (multi)polygon geometry.

Optionally, a specific random seed can be used when generating points. If seed is 0, then a completely random sequence of points will be generated.

If the source geometry is not a (multi)polygon, an empty list will be returned.

The optional feedback argument can be used to provide cancellation support during the point generation.

Since
QGIS 3.10

◆ removeDuplicateNodes()

bool QgsGeometry::removeDuplicateNodes ( double  epsilon = 4 * std::numeric_limits<double>::epsilon(),
bool  useZValues = false 
)

Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerate geometry.

The epsilon parameter specifies the tolerance for coordinates when determining that vertices are identical.

By default, z values are not considered when detecting duplicate nodes. E.g. two nodes with the same x and y coordinate but different z values will still be considered duplicate and one will be removed. If useZValues is true, then the z values are also tested and nodes with the same x and y but different z will be maintained.

Note that duplicate nodes are not tested between different parts of a multipart geometry. E.g. a multipoint geometry with overlapping points will not be changed by this method.

The function will return true if nodes were removed, or false if no duplicate nodes were found.

Definition at line 1493 of file qgsgeometry.cpp.

◆ removeInteriorRings()

QgsGeometry QgsGeometry::removeInteriorRings ( double  minimumAllowedArea = -1) const

Removes the interior rings from a (multi)polygon geometry.

If the minimumAllowedArea parameter is specified then only rings smaller than this minimum area will be removed.

Definition at line 1090 of file qgsgeometry.cpp.

◆ requiresConversionToStraightSegments()

bool QgsGeometry::requiresConversionToStraightSegments ( ) const

Returns true if the geometry is a curved geometry type which requires conversion to display as straight line segments.

See also
convertToStraightSegment

Definition at line 3617 of file qgsgeometry.cpp.

◆ reshapeGeometry()

Qgis::GeometryOperationResult QgsGeometry::reshapeGeometry ( const QgsLineString reshapeLineString)

Replaces a part of this geometry with another line.

Returns
OperationResult a result code: success or reason of failure

Definition at line 1237 of file qgsgeometry.cpp.

◆ rotate()

Qgis::GeometryOperationResult QgsGeometry::rotate ( double  rotation,
const QgsPointXY center 
)

Rotate this geometry around the Z axis.

Parameters
rotationclockwise rotation in degrees
centerrotation center
Returns
OperationResult a result code: success or reason of failure

Definition at line 1139 of file qgsgeometry.cpp.

◆ roundWaves()

QgsGeometry QgsGeometry::roundWaves ( double  wavelength,
double  amplitude,
bool  strictWavelength = false 
) const

Constructs rounded (sine-like) waves along the boundary of the geometry, with the specified wavelength and amplitude.

By default the wavelength argument is treated as a "maximum wavelength", where the actual wavelength will be dynamically adjusted so that an exact number of waves are created along the boundaries of the geometry. If strictWavelength is set to true then the wavelength will be used exactly and an incomplete pattern may be used for the final waveform.

See also
roundWavesRandomized()
Since
QGIS 3.24

Definition at line 1466 of file qgsgeometry.cpp.

◆ roundWavesRandomized()

QgsGeometry QgsGeometry::roundWavesRandomized ( double  minimumWavelength,
double  maximumWavelength,
double  minimumAmplitude,
double  maximumAmplitude,
unsigned long  seed = 0 
) const

Constructs randomized rounded (sine-like) waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.

The minimumWavelength and maximumWavelength arguments set the range for the randomized wavelength. This is evaluated for each individual waveform created along the geometry boundaries, so the resultant geometry will consist of many different wavelengths.

Similarly, the minimumAmplitude and maximumAmplitude arguments define the range for the randomized amplitude of the square components. Randomized amplitude values will be calculated individually for waves placed on each either side of the input geometry boundaries.

Optionally, a specific random seed can be used when generating points. If seed is 0, then a completely random sequence of points will be generated.

See also
squareWaves()
Since
QGIS 3.24

Definition at line 1472 of file qgsgeometry.cpp.

◆ set()

void QgsGeometry::set ( QgsAbstractGeometry geometry)

Sets the underlying geometry store.

Ownership of geometry is transferred.

Note
In QGIS 2.x this method was named setGeometry().
This method is deprecated for usage in Python and will be removed from Python bindings with QGIS 4. Using this method will confuse Python's memory management and type information system. Better create a new QgsGeometry object instead.
See also
get()
constGet()

Definition at line 139 of file qgsgeometry.cpp.

◆ sharedPaths()

QgsGeometry QgsGeometry::sharedPaths ( const QgsGeometry other) const

Find paths shared between the two given lineal geometries (this and other).

Returns a GeometryCollection having two elements:

  • first element is a MultiLineString containing shared paths having the same direction on both inputs
  • second element is a MultiLineString containing shared paths having the opposite direction on the two inputs

Returns a null geometry on exception.

Since
QGIS 3.20

Definition at line 2881 of file qgsgeometry.cpp.

◆ shortestLine()

QgsGeometry QgsGeometry::shortestLine ( const QgsGeometry other) const

Returns the shortest line joining this geometry to another geometry.

See also
nearestPoint()
Warning
QgsGeometry objects are inherently Cartesian/planar geometries, and the line returned by this method is calculated using strictly Cartesian mathematics. See QgsDistanceArea for similar methods which account for the curvature of an ellipsoidal body such as the Earth.

Definition at line 884 of file qgsgeometry.cpp.

◆ simplify()

QgsGeometry QgsGeometry::simplify ( double  tolerance) const

Returns a simplified version of this geometry using a specified tolerance value.

Definition at line 2593 of file qgsgeometry.cpp.

◆ simplifyCoverageVW()

QgsGeometry QgsGeometry::simplifyCoverageVW ( double  tolerance,
bool  preserveBoundary 
) const

Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geometry) to apply a Visvalingam–Whyatt simplification to the edges, reducing complexity in proportion with the provided tolerance, while retaining a valid coverage (no edges will cross or touch after the simplification).

Geometries never disappear, but they may be simplified down to just a triangle. Also, some invalid geoms (such as Polygons which have too few non-repeated points) will be returned unchanged.

If the input dataset is not a valid coverage due to overlaps, it will still be simplified, but invalid topology such as crossing edges will still be invalid.

Parameters
toleranceA tolerance parameter in linear units.
preserveBoundarySet to true to preserve the outside edges of the coverage without simplification, or false to allow them to be simplified.

This method requires a QGIS build based on GEOS 3.12 or later.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.11 or earlier.
See also
validateCoverage()
Since
QGIS 3.36

Definition at line 2853 of file qgsgeometry.cpp.

◆ singleSidedBuffer()

QgsGeometry QgsGeometry::singleSidedBuffer ( double  distance,
int  segments,
Qgis::BufferSide  side,
Qgis::JoinStyle  joinStyle = Qgis::JoinStyle::Round,
double  miterLimit = 2.0 
) const

Returns a single sided buffer for a (multi)line geometry.

The buffer is only applied to one side of the line.

Parameters
distancebuffer distance
segmentsfor round joins, number of segments to approximate quarter-circle
sideside of geometry to buffer
joinStylejoin style for corners
miterLimitlimit on the miter ratio used for very sharp corners
Returns
buffered geometry, or an empty geometry if buffer could not be calculated
See also
buffer()
taperedBuffer()

Definition at line 2495 of file qgsgeometry.cpp.

◆ smooth()

QgsGeometry QgsGeometry::smooth ( unsigned int  iterations = 1,
double  offset = 0.25,
double  minimumDistance = -1.0,
double  maxAngle = 180.0 
) const

Smooths a geometry by rounding off corners using the Chaikin algorithm.

This operation roughly doubles the number of vertices in a geometry.

If input geometries contain Z or M values, these will also be smoothed and the output geometry will retain the same dimensionality as the input geometry.

Parameters
iterationsnumber of smoothing iterations to run. More iterations results in a smoother geometry
offsetfraction of line to create new vertices along, between 0 and 1.0, e.g., the default value of 0.25 will create new vertices 25% and 75% along each line segment of the geometry for each iteration. Smaller values result in "tighter" smoothing.
minimumDistanceminimum segment length to apply smoothing to
maxAnglemaximum angle at node (0-180) at which smoothing will be applied

Definition at line 3983 of file qgsgeometry.cpp.

◆ snappedToGrid()

QgsGeometry QgsGeometry::snappedToGrid ( double  hSpacing,
double  vSpacing,
double  dSpacing = 0,
double  mSpacing = 0 
) const

Returns a new geometry with all points or vertices snapped to the closest point of the grid.

If the gridified geometry could not be calculated (or was totally collapsed) an empty geometry will be returned. Note that snapping to grid may generate an invalid geometry in some corner cases. It can also be thought as rounding the edges and it may be useful for removing errors.

Parameters
hSpacingHorizontal spacing of the grid (x axis). 0 to disable.
vSpacingVertical spacing of the grid (y axis). 0 to disable.
dSpacingDepth spacing of the grid (z axis). 0 (default) to disable.
mSpacingCustom dimension spacing of the grid (m axis). 0 (default) to disable.

Definition at line 1484 of file qgsgeometry.cpp.

◆ splitGeometry() [1/3]

Qgis::GeometryOperationResult QgsGeometry::splitGeometry ( const QgsCurve curve,
QVector< QgsGeometry > &  newGeometries,
bool  preserveCircular,
bool  topological,
QgsPointSequence topologyTestPoints,
bool  splitFeature = true 
)

Splits this geometry according to a given curve.

Parameters
curvethe curve that splits the geometry
[out]newGeometrieslist of new geometries that have been created with the splitLine. If the geometry is 3D, a linear interpolation of the z value is performed on the geometry at split points, see example.
preserveCircularwhether if circular strings are preserved after splitting
topologicaltrue if topological editing is enabled
[out]topologyTestPointspoints that need to be tested for topological completeness in the dataset
splitFeatureSet to true if you want to split a feature, otherwise set to false to split parts
Returns
OperationResult a result code: success or reason of failure
Since
QGIS 3.16

Definition at line 1217 of file qgsgeometry.cpp.

◆ splitGeometry() [2/3]

Qgis::GeometryOperationResult QgsGeometry::splitGeometry ( const QgsPointSequence splitLine,
QVector< QgsGeometry > &  newGeometries,
bool  topological,
QgsPointSequence topologyTestPoints,
bool  splitFeature = true,
bool  skipIntersectionTest = false 
)

Splits this geometry according to a given line.

Parameters
splitLinethe line that splits the geometry
[out]newGeometrieslist of new geometries that have been created with the splitLine. If the geometry is 3D, a linear interpolation of the z value is performed on the geometry at split points, see example.
topologicaltrue if topological editing is enabled
[out]topologyTestPointspoints that need to be tested for topological completeness in the dataset
splitFeatureSet to true if you want to split a feature, otherwise set to false to split parts
skipIntersectionTestset to true to skip the potentially expensive initial intersection check. Only set this flag if an intersection test has already been performed by the caller! Not available in Python bindings.
Returns
Qgis::GeometryOperationResult a result code: success or reason of failure

Example:

geometry = QgsGeometry.fromWkt('CompoundCurveZ ((2749546.2003820720128715 1262904.45356595050543547 100, 2749557.82053794478997588 1262920.05570670193992555 200))')
split_line = [QgsPoint(2749544.19, 1262914.79), QgsPoint(2749557.64, 1262897.30)]
result, new_geometries, point_xy = geometry.splitGeometry(split_line, False)
print(geometry.asWkt(2))
> LineStringZ (2749549.12 1262908.38 125.14, 2749557.82 1262920.06 200)
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49

Definition at line 1164 of file qgsgeometry.cpp.

◆ splitGeometry() [3/3]

Qgis::GeometryOperationResult QgsGeometry::splitGeometry ( const QVector< QgsPointXY > &  splitLine,
QVector< QgsGeometry > &  newGeometries,
bool  topological,
QVector< QgsPointXY > &  topologyTestPoints,
bool  splitFeature = true 
)

Splits this geometry according to a given line.

Parameters
splitLinethe line that splits the geometry
[out]newGeometrieslist of new geometries that have been created with the split
topologicaltrue if topological editing is enabled
[out]topologyTestPointspoints that need to be tested for topological completeness in the dataset
splitFeatureSet to true if you want to split a feature, otherwise set to false to split parts
Returns
Qgis::GeometryOperationResult a result code: success or reason of failure
Deprecated:
QGIS 3.12. Will be removed in QGIS 4.0. Use the variant which accepts QgsPoint objects instead of QgsPointXY.

Definition at line 1155 of file qgsgeometry.cpp.

◆ sqrDistToVertexAt()

double QgsGeometry::sqrDistToVertexAt ( QgsPointXY point,
int  atVertex 
) const

Returns the squared Cartesian distance between the given point to the given vertex index (vertex at the given position number, ring and item (first number is index 0))

Definition at line 863 of file qgsgeometry.cpp.

◆ squareWaves()

QgsGeometry QgsGeometry::squareWaves ( double  wavelength,
double  amplitude,
bool  strictWavelength = false 
) const

Constructs square waves along the boundary of the geometry, with the specified wavelength and amplitude.

By default the wavelength argument is treated as a "maximum wavelength", where the actual wavelength will be dynamically adjusted so that an exact number of square waves are created along the boundaries of the geometry. If strictWavelength is set to true then the wavelength will be used exactly and an incomplete pattern may be used for the final waveform.

See also
squareWavesRandomized()
Since
QGIS 3.24

Definition at line 1454 of file qgsgeometry.cpp.

◆ squareWavesRandomized()

QgsGeometry QgsGeometry::squareWavesRandomized ( double  minimumWavelength,
double  maximumWavelength,
double  minimumAmplitude,
double  maximumAmplitude,
unsigned long  seed = 0 
) const

Constructs randomized square waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.

The minimumWavelength and maximumWavelength arguments set the range for the randomized wavelength. This is evaluated for each individual square waveform created along the geometry boundaries, so the resultant geometry will consist of many different wavelengths.

Similarly, the minimumAmplitude and maximumAmplitude arguments define the range for the randomized amplitude of the square components. Randomized amplitude values will be calculated individually for squares placed on each either side of the input geometry boundaries.

Optionally, a specific random seed can be used when generating points. If seed is 0, then a completely random sequence of points will be generated.

See also
squareWaves()
Since
QGIS 3.24

Definition at line 1460 of file qgsgeometry.cpp.

◆ subdivide()

QgsGeometry QgsGeometry::subdivide ( int  maxNodes = 256,
const QgsGeometryParameters parameters = QgsGeometryParameters() 
) const

Subdivides the geometry.

The returned geometry will be a collection containing subdivided parts from the original geometry, where no part has more then the specified maximum number of nodes (maxNodes).

This is useful for dividing a complex geometry into less complex parts, which are better able to be spatially indexed and faster to perform further operations such as intersects on. The returned geometry parts may not be valid and may contain self-intersections.

The minimum allowed value for maxNodes is 8.

Curved geometries will be segmentized before subdivision.

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Since QGIS 3.28 the optional parameters argument can be used to specify parameters which control the subdivision results.

Definition at line 2895 of file qgsgeometry.cpp.

◆ symDifference()

QgsGeometry QgsGeometry::symDifference ( const QgsGeometry geometry,
const QgsGeometryParameters parameters = QgsGeometryParameters() 
) const

Returns a geometry representing the points making up this geometry that do not make up other.

If the input is a NULL geometry, the output will also be a NULL geometry.

If an error was encountered while creating the result, more information can be retrieved by calling lastError() on the returned geometry.

Since QGIS 3.28 the optional parameters argument can be used to specify parameters which control the difference results.

Definition at line 3130 of file qgsgeometry.cpp.

◆ taperedBuffer()

QgsGeometry QgsGeometry::taperedBuffer ( double  startWidth,
double  endWidth,
int  segments 
) const

Calculates a variable width buffer ("tapered buffer") for a (multi)curve geometry.

The buffer begins at a width of startWidth at the start of each curve, and ends at a width of endWidth. Note that unlike buffer() methods, startWidth and endWidth are the diameter of the buffer at these points, not the radius.

The segments argument specifies the number of segments to approximate quarter-circle curves in the buffer.

Non (multi)curve input geometries will return a null output geometry.

See also
buffer()
singleSidedBuffer()
variableWidthBufferByM()
Since
QGIS 3.2

Definition at line 2539 of file qgsgeometry.cpp.

◆ toggleCircularAtVertex()

bool QgsGeometry::toggleCircularAtVertex ( int  atVertex)

Converts the vertex at the given position from/to circular.

Returns
false if atVertex does not correspond to a valid vertex on this geometry (including if this geometry is a Point), or if the specified vertex can't be converted (e.g. start/end points).
Since
QGIS 3.20

Definition at line 681 of file qgsgeometry.cpp.

◆ touches()

bool QgsGeometry::touches ( const QgsGeometry geometry) const

Returns true if the geometry touches another geometry.

Note
For performance critical code, or when testing for touches against many different geometries, consider using QgsGeometryEngine instead. This approach can be many orders of magnitude faster than calling touches() directly. See createGeometryEngine() for details on how to use the QgsGeometryEngine class.

Definition at line 1626 of file qgsgeometry.cpp.

◆ transform() [1/2]

Qgis::GeometryOperationResult QgsGeometry::transform ( const QgsCoordinateTransform ct,
Qgis::TransformDirection  direction = Qgis::TransformDirection::Forward,
bool  transformZ = false 
)

Transforms this geometry as described by the coordinate transform ct.

The transformation defaults to a forward transform, but the direction can be swapped by setting the direction argument.

By default, z-coordinates are not transformed, even if the coordinate transform includes a vertical datum transformation. To transform z-coordinates, set transformZ to true. This requires that the z coordinates in the geometry represent height relative to the vertical datum of the source CRS (generally ellipsoidal heights) and are expressed in its vertical units (generally meters).

Returns
OperationResult a result code: success or reason of failure

Definition at line 3627 of file qgsgeometry.cpp.

◆ transform() [2/2]

Qgis::GeometryOperationResult QgsGeometry::transform ( const QTransform &  t,
double  zTranslate = 0.0,
double  zScale = 1.0,
double  mTranslate = 0.0,
double  mScale = 1.0 
)

Transforms the x and y components of the geometry using a QTransform object t.

Optionally, the geometry's z values can be scaled via zScale and translated via zTranslate. Similarly, m-values can be scaled via mScale and translated via mTranslate.

Returns
OperationResult a result code: success or reason of failure

Definition at line 3639 of file qgsgeometry.cpp.

◆ transformVertices()

void QgsGeometry::transformVertices ( const std::function< QgsPoint(const QgsPoint &) > &  transform)

Transforms the vertices from the geometry in place, applying the transform function to every vertex.

Depending on the transform used, this may result in an invalid geometry.

Transform functions are not permitted to alter the dimensionality of vertices. If a transform which adds (or removes) z/m values is desired, first call the corresponding addZValue() or addMValue() function to change the geometry's dimensionality and then transform.

Note
Not available in Python bindings
Since
QGIS 3.4

Definition at line 3822 of file qgsgeometry.cpp.

◆ translate()

Qgis::GeometryOperationResult QgsGeometry::translate ( double  dx,
double  dy,
double  dz = 0.0,
double  dm = 0.0 
)

Translates this geometry by dx, dy, dz and dm.

Returns
OperationResult a result code: success or reason of failure

Definition at line 1126 of file qgsgeometry.cpp.

◆ triangularWaves()

QgsGeometry QgsGeometry::triangularWaves ( double  wavelength,
double  amplitude,
bool  strictWavelength = false 
) const

Constructs triangular waves along the boundary of the geometry, with the specified wavelength and amplitude.

By default the wavelength argument is treated as a "maximum wavelength", where the actual wavelength will be dynamically adjusted so that an exact number of triangular waves are created along the boundaries of the geometry. If strictWavelength is set to true then the wavelength will be used exactly and an incomplete pattern may be used for the final waveform.

See also
triangularWavesRandomized()
Since
QGIS 3.24

Definition at line 1442 of file qgsgeometry.cpp.

◆ triangularWavesRandomized()

QgsGeometry QgsGeometry::triangularWavesRandomized ( double  minimumWavelength,
double  maximumWavelength,
double  minimumAmplitude,
double  maximumAmplitude,
unsigned long  seed = 0 
) const

Constructs randomized triangular waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.

The minimumWavelength and maximumWavelength arguments set the range for the randomized wavelength. This is evaluated for each individual triangular waveform created along the geometry boundaries, so the resultant geometry will consist of many different wavelengths.

Similarly, the minimumAmplitude and maximumAmplitude arguments define the range for the randomized amplitude of the triangular components. Randomized amplitude values will be calculated individually for triangles placed on each either side of the input geometry boundaries.

Optionally, a specific random seed can be used when generating points. If seed is 0, then a completely random sequence of points will be generated.

See also
triangularWaves()
Since
QGIS 3.24

Definition at line 1448 of file qgsgeometry.cpp.

◆ type()

Qgis::GeometryType QgsGeometry::type ( ) const

Returns type of the geometry as a Qgis::GeometryType.

See also
wkbType

Definition at line 504 of file qgsgeometry.cpp.

◆ unaryUnion()

QgsGeometry QgsGeometry::unaryUnion ( const QVector< QgsGeometry > &  geometries,
const QgsGeometryParameters parameters = QgsGeometryParameters() 
)
static

Compute the unary union on a list of geometries.

May be faster than an iterative union on a set of geometries. The returned geometry will be fully noded, i.e. a node will be created at every common intersection of the input geometries. An empty geometry will be returned in the case of errors.

Since QGIS 3.28 the optional parameters argument can be used to specify parameters which control the union results.

Definition at line 3578 of file qgsgeometry.cpp.

◆ unionCoverage()

QgsGeometry QgsGeometry::unionCoverage ( ) const

Optimized union algorithm for polygonal inputs that are correctly noded and do not overlap.

It may generate an error (returning a null geometry) for inputs that do not satisfy this constraint, however this is not guaranteed.

The input geometry is the polygonal coverage to union, stored in a geometry collection. All members must be POLYGON or MULTIPOLYGON.

See also
validateCoverage()
Since
QGIS 3.36

Definition at line 2815 of file qgsgeometry.cpp.

◆ validateCoverage()

Qgis::CoverageValidityResult QgsGeometry::validateCoverage ( double  gapWidth,
QgsGeometry invalidEdges = nullptr 
) const

Analyze a coverage (represented as a collection of polygonal geometry with exactly matching edge geometry) to find places where the assumption of exactly matching edges is not met.

The input geometry is the polygonal coverage to access, stored in a geometry collection. All members must be POLYGON or MULTIPOLYGON.

Parameters
gapWidthThe maximum width of gaps to detect.
invalidEdgesWhen there are invalidities in the coverage, will be set with a geometry collection of the same length as the input, with a MULTILINESTRING of the error edges for each invalid polygon, or an EMPTY where the polygon is a valid participant in the coverage.
Returns
validity check result

This method requires a QGIS build based on GEOS 3.12 or later.

Exceptions
QgsNotSupportedExceptionon QGIS builds based on GEOS 3.11 or earlier.
See also
simplifyCoverageVW()
Since
QGIS 3.36

Definition at line 2834 of file qgsgeometry.cpp.

◆ validateGeometry()

void QgsGeometry::validateGeometry ( QVector< QgsGeometry::Error > &  errors,
Qgis::GeometryValidationEngine  method = Qgis::GeometryValidationEngine::QgisInternal,
Qgis::GeometryValidityFlags  flags = Qgis::GeometryValidityFlags() 
) const

Validates geometry and produces a list of geometry errors.

The method argument dictates which validator to utilize.

The flags parameter indicates optional flags which control the type of validity checking performed.

Definition at line 3467 of file qgsgeometry.cpp.

◆ variableWidthBufferByM()

QgsGeometry QgsGeometry::variableWidthBufferByM ( int  segments) const

Calculates a variable width buffer for a (multi)linestring geometry, where the width at each node is taken from the linestring m values.

The segments argument specifies the number of segments to approximate quarter-circle curves in the buffer.

Non (multi)linestring input geometries will return a null output geometry.

See also
buffer()
singleSidedBuffer()
taperedBuffer()
Since
QGIS 3.2

Definition at line 2546 of file qgsgeometry.cpp.

◆ vertexAt()

QgsPoint QgsGeometry::vertexAt ( int  atVertex) const

Returns coordinates of a vertex.

Parameters
atVertexindex of the vertex
Returns
Coordinates of the vertex or empty QgsPoint on error

Definition at line 847 of file qgsgeometry.cpp.

◆ vertexIdFromVertexNr()

bool QgsGeometry::vertexIdFromVertexNr ( int  number,
QgsVertexId id 
) const

Calculates the vertex ID from a vertex number.

If a matching vertex was found, it will be stored in id.

Returns true if vertex was found.

See also
vertexNrFromVertexId()

Definition at line 3762 of file qgsgeometry.cpp.

◆ vertexNrFromVertexId()

int QgsGeometry::vertexNrFromVertexId ( QgsVertexId  id) const

Returns the vertex number corresponding to a vertex id.

The vertex numbers start at 0, so a return value of 0 corresponds to the first vertex.

Returns -1 if a corresponding vertex could not be found.

See also
vertexIdFromVertexNr()

Definition at line 3798 of file qgsgeometry.cpp.

◆ vertices()

QgsVertexIterator QgsGeometry::vertices ( ) const

Returns a read-only, Java-style iterator for traversal of vertices of all the geometry, including all geometry parts and rings.

Warning
The iterator returns a copy of individual vertices, and accordingly geometries cannot be modified using the iterator. See transformVertices() for a safe method to modify vertices "in-place".

Example

# print the x and y coordinate for each vertex in a LineString
geometry = QgsGeometry.fromWkt( 'LineString( 0 0, 1 1, 2 2)' )
for v in geometry.vertices():
print(v.x(), v.y())
# vertex iteration includes all parts and rings
geometry = QgsGeometry.fromWkt( 'MultiPolygon((( 0 0, 0 10, 10 10, 10 0, 0 0 ),( 5 5, 5 6, 6 6, 6 5, 5 5)),((20 2, 22 2, 22 4, 20 4, 20 2)))' )
for v in geometry.vertices():
print(v.x(), v.y())
See also
parts()

Definition at line 2345 of file qgsgeometry.cpp.

◆ vertices_begin()

QgsAbstractGeometry::vertex_iterator QgsGeometry::vertices_begin ( ) const

Returns STL-style iterator pointing to the first vertex of the geometry.

Definition at line 2331 of file qgsgeometry.cpp.

◆ vertices_end()

QgsAbstractGeometry::vertex_iterator QgsGeometry::vertices_end ( ) const

Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.

Definition at line 2338 of file qgsgeometry.cpp.

◆ voronoiDiagram()

QgsGeometry QgsGeometry::voronoiDiagram ( const QgsGeometry extent = QgsGeometry(),
double  tolerance = 0.0,
bool  edgesOnly = false 
) const

Creates a Voronoi diagram for the nodes contained within the geometry.

Returns the Voronoi polygons for the nodes contained within the geometry. If extent is specified then it will be used as a clipping envelope for the diagram. If no extent is set then the clipping envelope will be automatically calculated. In either case the diagram will be clipped to the larger of the provided envelope OR the envelope surrounding all input nodes. The tolerance parameter specifies an optional snapping tolerance which can be used to improve the robustness of the diagram calculation. If edgesOnly is true than line string boundary geometries will be returned instead of polygons. An empty geometry will be returned if the diagram could not be calculated.

Definition at line 2773 of file qgsgeometry.cpp.

◆ within()

bool QgsGeometry::within ( const QgsGeometry geometry) const

Returns true if the geometry is completely within another geometry.

Note
For performance critical code, or when testing for within against many different geometries, consider using QgsGeometryEngine instead. This approach can be many orders of magnitude faster than calling within() directly. See createGeometryEngine() for details on how to use the QgsGeometryEngine class.

Definition at line 1650 of file qgsgeometry.cpp.

◆ wkbSize()

int QgsGeometry::wkbSize ( QgsAbstractGeometry::WkbFlags  flags = QgsAbstractGeometry::WkbFlags()) const

Returns the length of the QByteArray returned by asWkb()

The optional flags argument specifies flags controlling WKB export behavior

Since
QGIS 3.16

Definition at line 3182 of file qgsgeometry.cpp.

◆ wkbType()

Qgis::WkbType QgsGeometry::wkbType ( ) const

Returns type of the geometry as a WKB type (point / linestring / polygon etc.)

See also
type

Definition at line 492 of file qgsgeometry.cpp.

Friends And Related Symbol Documentation

◆ QgsInternalGeometryEngine

friend class QgsInternalGeometryEngine
friend

Definition at line 3244 of file qgsgeometry.h.

Property Documentation

◆ isNull

bool QgsGeometry::isNull
read

Definition at line 164 of file qgsgeometry.h.

◆ type

Qgis::GeometryType QgsGeometry::type
read

Definition at line 165 of file qgsgeometry.h.


The documentation for this class was generated from the following files: