QgsGeometry class

A geometry is the spatial representation of a feature.

Since QGIS 2.10, QgsGeometry acts as a generic container for geometry objects. QgsGeometry is 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.

Public types

enum BufferSide { SideLeft = 0, SideRight }
Side of line to buffer.
enum EndCapStyle { CapRound = 1, CapFlat, CapSquare }
End cap styles for buffers.
enum JoinStyle { JoinStyleRound = 1, JoinStyleMiter, JoinStyleBevel }
Join styles for buffers.
enum OperationResult { Success = 0, NothingHappened = 1000, InvalidBaseGeometry, InvalidInputGeometryType, SelectionIsEmpty, SelectionIsGreaterThanOne, GeometryEngineError, LayerNotEditable, AddPartSelectedGeometryNotFound, AddPartNotMultiGeometry, AddRingNotClosed, AddRingNotValid, AddRingCrossesExistingRings, AddRingNotInExistingFeature, SplitCannotSplitPoint }
Success or failure of a geometry operation.
enum ValidationMethod { ValidatorQgisInternal, ValidatorGeos }
Available methods for validating geometries.

Public static functions

static auto collectGeometry(const QVector<QgsGeometry>& geometries) -> QgsGeometry
Creates a new multipart geometry from a list of QgsGeometry objects.
static auto compare(const QgsPolylineXY& p1, const QgsPolylineXY& p2, double epsilon = 4*std::numeric_limits<double>::epsilon()) -> bool
Compares two polylines for equality within a specified tolerance.
static auto compare(const QgsPolygonXY& p1, const QgsPolygonXY& p2, double epsilon = 4*std::numeric_limits<double>::epsilon()) -> bool
Compares two polygons for equality within a specified tolerance.
static auto compare(const QgsMultiPolygonXY& p1, const QgsMultiPolygonXY& p2, double epsilon = 4*std::numeric_limits<double>::epsilon()) -> bool
Compares two multipolygons for equality within a specified tolerance.
static void convertPointList(const QVector<QgsPointXY>& input, QgsPointSequence& output)
Upgrades a point list from QgsPointXY to QgsPoint.
static void convertPointList(const QgsPointSequence& input, QVector<QgsPointXY>& output)
Downgrades a point list from QgsPoint to QgsPointXY.
static auto createGeometryEngine(const QgsAbstractGeometry* geometry) -> QgsGeometryEngine*
Creates and returns a new geometry engine.
static auto createPolygonFromQPolygonF(const QPolygonF& polygon) -> QgsPolygonXY
Creates a QgsPolygonXYfrom a QPolygonF.
static auto createPolylineFromQPolygonF(const QPolygonF& polygon) -> QgsPolylineXY
Creates a QgsPolylineXY from a QPolygonF.
static auto createWedgeBuffer(const QgsPoint& center, double azimuth, double angularWidth, double outerRadius, double innerRadius = 0) -> QgsGeometry
Creates a wedge shaped buffer from a center point.
static auto fromMultiPointXY(const QgsMultiPointXY& multipoint) -> QgsGeometry
Creates a new geometry from a QgsMultiPointXY object.
static auto fromMultiPolygonXY(const QgsMultiPolygonXY& multipoly) -> QgsGeometry
Creates a new geometry from a QgsMultiPolygon.
static auto fromMultiPolylineXY(const QgsMultiPolylineXY& multiline) -> QgsGeometry
Creates a new geometry from a QgsMultiPolylineXY object.
static auto fromPointXY(const QgsPointXY& point) -> QgsGeometry
Creates a new geometry from a QgsPointXY object.
static auto fromPolygonXY(const QgsPolygonXY& polygon) -> QgsGeometry
Creates a new geometry from a QgsPolygon.
static auto fromPolyline(const QgsPolyline& polyline) -> QgsGeometry
Creates a new LineString geometry from a list of QgsPoint points.
static auto fromPolylineXY(const QgsPolylineXY& polyline) -> QgsGeometry
Creates a new LineString geometry from a list of QgsPointXY points.
static auto fromQPointF(QPointF point) -> QgsGeometry
Construct geometry from a QPointF.
static auto fromQPolygonF(const QPolygonF& polygon) -> QgsGeometry
Construct geometry from a QPolygonF.
static auto fromRect(const QgsRectangle& rect) -> QgsGeometry
Creates a new geometry from a QgsRectangle.
static auto fromWkt(const QString& wkt) -> QgsGeometry
Creates a new geometry from a WKT string.
static auto polygonize(const QVector<QgsGeometry>& geometries) -> QgsGeometry
Creates a GeometryCollection geometry containing possible polygons formed from the constituent linework of a set of geometries.
static auto unaryUnion(const QVector<QgsGeometry>& geometries) -> QgsGeometry
Compute the unary union on a list of geometries.

Constructors, destructors, conversion operators

QgsGeometry()
Constructor.
QgsGeometry(const QgsGeometry&)
Copy constructor will prompt a deep copy of the object.
QgsGeometry(QgsAbstractGeometry* geom) explicit
Creates a geometry from an abstract geometry object.
QgsGeometry(std::unique_ptr<QgsAbstractGeometry> geom) explicit
Creates a geometry from an abstract geometry object.
operator QVariant() const
Allows direct construction of QVariants from geometry.

Public functions

auto addPart(const QVector<QgsPointXY>& points, QgsWkbTypes::GeometryType geomType = QgsWkbTypes::UnknownGeometry) -> OperationResult
Adds a new part to a the geometry.
auto addPart(const QgsPointSequence& points, QgsWkbTypes::GeometryType geomType = QgsWkbTypes::UnknownGeometry) -> OperationResult
Adds a new part to a the geometry.
auto addPart(QgsAbstractGeometry* part, QgsWkbTypes::GeometryType geomType = QgsWkbTypes::UnknownGeometry) -> OperationResult
Adds a new part to this geometry.
auto addPart(const QgsGeometry& newPart) -> OperationResult
Adds a new island polygon to a multipolygon feature.
auto addRing(const QVector<QgsPointXY>& ring) -> OperationResult
Adds a new ring to this geometry.
auto addRing(QgsCurve* ring) -> OperationResult
Adds a new ring to this geometry.
void adjacentVertices(int atVertex, int& beforeVertex, int& afterVertex) const
Returns the indexes of the vertices before and after the given vertex index.
auto angleAtVertex(int vertex) const -> double
Returns the bisector angle for this geometry at the specified vertex.
auto area() const -> double
Returns the area of the geometry using GEOS.
auto asGeometryCollection() const -> QVector<QgsGeometry>
Returns contents of the geometry as a list of geometries.
auto asJson(int precision = 17) const -> QString
Exports the geometry to a GeoJSON string.
auto asMultiPoint() const -> QgsMultiPointXY
Returns the contents of the geometry as a multi-point.
auto asMultiPolygon() const -> QgsMultiPolygonXY
Returns the contents of the geometry as a multi-polygon.
auto asMultiPolyline() const -> QgsMultiPolylineXY
Returns the contents of the geometry as a multi-linestring.
auto asPoint() const -> QgsPointXY
Returns the contents of the geometry as a 2-dimensional point.
auto asPolygon() const -> QgsPolygonXY
Returns the contents of the geometry as a polygon.
auto asPolyline() const -> QgsPolylineXY
Returns the contents of the geometry as a polyline.
auto asQPointF() const -> QPointF
Returns contents of the geometry as a QPointF if wkbType is WKBPoint, otherwise returns a null QPointF.
auto asQPolygonF() const -> QPolygonF
Returns contents of the geometry as a QPolygonF.
auto asWkb() const -> QByteArray
Export the geometry to WKB.
auto asWkt(int precision = 17) const -> QString
Exports the geometry to WKT.
auto avoidIntersections(const QList<QgsVectorLayer*>& avoidIntersectionsLayers, const QHash<QgsVectorLayer*, QSet<QgsFeatureId>>& ignoreFeatures = (QHash<QgsVectorLayer*, QSet<QgsFeatureId>>())) -> int
Modifies geometry to avoid intersections with the layers specified in project properties.
auto boundingBox() const -> QgsRectangle
Returns the bounding box of the geometry.
auto boundingBoxIntersects(const QgsRectangle& rectangle) const -> bool
Returns true if the bounding box of this geometry intersects with a rectangle.
auto boundingBoxIntersects(const QgsGeometry& geometry) const -> bool
Returns true if the bounding box of this geometry intersects with the bounding box of another geometry.
auto buffer(double distance, int segments) const -> QgsGeometry
Returns a buffer region around this geometry having the given width and with a specified number of segments used to approximate curves.
auto buffer(double distance, int segments, EndCapStyle endCapStyle, JoinStyle joinStyle, double miterLimit) const -> QgsGeometry
Returns a buffer region around the geometry, with additional style options.
auto centroid() const -> QgsGeometry
Returns the center of mass of a geometry.
auto clipped(const QgsRectangle& rectangle) -> QgsGeometry
Clips the geometry using the specified rectangle.
auto closestSegmentWithContext(const QgsPointXY& point, QgsPointXY& minDistPoint, int& afterVertex, int* leftOf = nullptr, double epsilon = DEFAULT_SEGMENT_EPSILON) const -> double
Searches for the closest segment of geometry to the given point.
auto closestVertex(const QgsPointXY& point, int& atVertex, int& beforeVertex, int& afterVertex, double& sqrDist) const -> QgsPointXY
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.
auto closestVertexWithContext(const QgsPointXY& point, int& atVertex) const -> double
Searches for the closest vertex in this geometry to the given point.
auto combine(const QgsGeometry& geometry) const -> QgsGeometry
Returns a geometry representing all the points in this geometry and other (a union geometry operation).
auto const_parts_begin() const -> QgsAbstractGeometry::const_part_iterator
Returns STL-style const iterator pointing to the first part of the geometry.
auto const_parts_end() const -> QgsAbstractGeometry::const_part_iterator
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
auto constGet() const -> const QgsAbstractGeometry*
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
auto constParts() const -> QgsGeometryConstPartIterator
Returns Java-style iterator for traversal of parts of the geometry.
auto contains(const QgsPointXY* p) const -> bool
Tests for containment of a point (uses GEOS)
auto contains(const QgsGeometry& geometry) const -> bool
Tests for if geometry is contained in another (uses GEOS)
auto convertGeometryCollectionToSubclass(QgsWkbTypes::GeometryType geomType) -> bool
Converts geometry collection to a the desired geometry type subclass (multi-point, multi-linestring or multi-polygon).
auto convertToMultiType() -> bool
Converts single type geometry into multitype geometry e.g.
auto convertToSingleType() -> bool
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.
auto convertToType(QgsWkbTypes::GeometryType destType, bool destMultipart = false) const -> QgsGeometry
Try to convert the geometry to the requested type.
auto convexHull() const -> QgsGeometry
Returns the smallest convex polygon that contains all the points in the geometry.
auto crosses(const QgsGeometry& geometry) const -> bool
Test for if geometry crosses another (uses GEOS)
auto delaunayTriangulation(double tolerance = 0.0, bool edgesOnly = false) const -> QgsGeometry
Returns the Delaunay triangulation for the vertices of the geometry.
auto deletePart(int partNum) -> bool
Deletes part identified by the part number.
auto deleteRing(int ringNum, int partNum = 0) -> bool
Deletes a ring in polygon or multipolygon.
auto deleteVertex(int atVertex) -> bool
Deletes the vertex at the given position number and item (first number is index 0)
auto densifyByCount(int extraNodesPerSegment) const -> QgsGeometry
Returns a copy of the geometry which has been densified by adding the specified number of extra nodes within each segment of the geometry.
auto densifyByDistance(double distance) const -> QgsGeometry
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.
auto difference(const QgsGeometry& geometry) const -> QgsGeometry
Returns a geometry representing the points making up this geometry that do not make up other.
auto disjoint(const QgsGeometry& geometry) const -> bool
Tests for if geometry is disjoint of another (uses GEOS)
auto distance(const QgsGeometry& geom) const -> double
Returns the minimum distance between this geometry and another geometry, using GEOS.
auto distanceToVertex(int vertex) const -> double
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.
auto equals(const QgsGeometry& geometry) const -> bool
Test if this geometry is exactly equal to another geometry.
auto extendLine(double startDistance, double endDistance) const -> QgsGeometry
Extends a (multi)line geometry by extrapolating out the start or end of the line by a specified distance.
auto extrude(double x, double y) -> QgsGeometry
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.
auto forceRHR() const -> QgsGeometry
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.
void fromWkb(unsigned char* wkb, int length)
Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length.
void fromWkb(const QByteArray& wkb)
Set the geometry, feeding in the buffer containing OGC Well-Known Binary.
auto get() -> QgsAbstractGeometry*
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
auto hausdorffDistance(const QgsGeometry& geom) const -> double
Returns the Hausdorff distance between this geometry and geom.
auto hausdorffDistanceDensify(const QgsGeometry& geom, double densifyFraction) const -> double
Returns the Hausdorff distance between this geometry and geom.
auto insertVertex(double x, double y, int beforeVertex) -> bool
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.
auto insertVertex(const QgsPoint& point, int beforeVertex) -> bool
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.
auto interpolate(double distance) const -> QgsGeometry
Returns an interpolated point on the geometry at the specified distance.
auto interpolateAngle(double distance) const -> double
Returns the angle parallel to the linestring or polygon boundary at the specified distance along the geometry.
auto intersection(const QgsGeometry& geometry) const -> QgsGeometry
Returns a geometry representing the points shared by this geometry and other.
auto intersects(const QgsRectangle& rectangle) const -> bool
Returns true if this geometry exactly intersects with a rectangle.
auto intersects(const QgsGeometry& geometry) const -> bool
Returns true if this geometry exactly intersects with another geometry.
auto isEmpty() const -> bool
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geometries).
auto isGeosEqual(const QgsGeometry&) const -> bool
Compares the geometry with another geometry using GEOS.
auto isGeosValid() const -> bool
Checks validity of the geometry using GEOS.
auto isMultipart() const -> bool
Returns true if WKB of the geometry is of WKBMulti* type.
auto isNull() const -> Q_INVOKABLE bool
Returns true if the geometry is null (ie, contains no underlying geometry accessible via geometry() ).
auto isSimple() const -> bool
Determines whether the geometry is simple (according to OGC definition), i.e.
auto lastError() const -> QString
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.
auto length() const -> double
Returns the length of geometry using GEOS.
auto lineLocatePoint(const QgsGeometry& point) const -> double
Returns a distance representing the location along this linestring of the closest point on this linestring geometry to the specified point.
auto makeDifference(const QgsGeometry& other) const -> QgsGeometry
Returns the geometry formed by modifying this geometry such that it does not intersect the other geometry.
auto makeDifferenceInPlace(const QgsGeometry& other) -> int
Changes this geometry such that it does not intersect the other geometry.
auto makeValid() const -> QgsGeometry
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.
auto mergeLines() const -> QgsGeometry
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line strings.
auto minimalEnclosingCircle(QgsPointXY& center, double& radius, unsigned int segments = 36) const -> QgsGeometry
Returns the minimal enclosing circle for the geometry.
auto minimalEnclosingCircle(unsigned int segments = 36) const -> QgsGeometry
Returns the minimal enclosing circle for the geometry.
auto moveVertex(double x, double y, int atVertex) -> bool
Moves the vertex at the given position number and item (first number is index 0) to the given coordinates.
auto moveVertex(const QgsPoint& p, int atVertex) -> bool
Moves the vertex at the given position number and item (first number is index 0) to the given coordinates.
auto nearestPoint(const QgsGeometry& other) const -> QgsGeometry
Returns the nearest point on this geometry to another geometry.
auto offsetCurve(double distance, int segments, JoinStyle joinStyle, double miterLimit) const -> QgsGeometry
Returns an offset line at a given distance and side from an input line.
auto operator=(QgsGeometry const& rhs) -> QgsGeometry&
Creates a deep copy of the object.
auto orientedMinimumBoundingBox(double& area, double& angle, double& width, double& height) const -> QgsGeometry
Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated rectangle which fully encompasses the geometry.
auto orientedMinimumBoundingBox() const -> QgsGeometry
Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated rectangle which fully encompasses the geometry.
auto orthogonalize(double tolerance = 1.0E-8, int maxIterations = 1000, double angleThreshold = 15.0) const -> QgsGeometry
Attempts to orthogonalize a line or polygon geometry by shifting vertices to make the geometries angles either right angles or flat lines.
auto overlaps(const QgsGeometry& geometry) const -> bool
Test for if geometry overlaps another (uses GEOS)
auto parts() -> QgsGeometryPartIterator
Returns Java-style iterator for traversal of parts of the geometry.
auto parts_begin() -> QgsAbstractGeometry::part_iterator
Returns STL-style iterator pointing to the first part of the geometry.
auto parts_end() -> QgsAbstractGeometry::part_iterator
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
auto pointOnSurface() const -> QgsGeometry
Returns a point guaranteed to lie on the surface of a geometry.
auto poleOfInaccessibility(double precision, double* distanceToBoundary = nullptr) const -> QgsGeometry
Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal point from the boundary of the surface.
auto removeDuplicateNodes(double epsilon = 4*std::numeric_limits<double>::epsilon(), bool useZValues = false) -> bool
Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerate geometry.
auto removeInteriorRings(double minimumAllowedArea = -1) const -> QgsGeometry
Removes the interior rings from a (multi)polygon geometry.
auto requiresConversionToStraightSegments() const -> bool
Returns true if the geometry is a curved geometry type which requires conversion to display as straight line segments.
auto reshapeGeometry(const QgsLineString& reshapeLineString) -> OperationResult
Replaces a part of this geometry with another line.
auto rotate(double rotation, const QgsPointXY& center) -> OperationResult
Rotate this geometry around the Z axis.
void set(QgsAbstractGeometry* geometry)
Sets the underlying geometry store.
auto shortestLine(const QgsGeometry& other) const -> QgsGeometry
Returns the shortest line joining this geometry to another geometry.
auto simplify(double tolerance) const -> QgsGeometry
Returns a simplified version of this geometry using a specified tolerance value.
auto singleSidedBuffer(double distance, int segments, BufferSide side, JoinStyle joinStyle = JoinStyleRound, double miterLimit = 2.0) const -> QgsGeometry
Returns a single sided buffer for a (multi)line geometry.
auto smooth(unsigned int iterations = 1, double offset = 0.25, double minimumDistance = -1.0, double maxAngle = 180.0) const -> QgsGeometry
Smooths a geometry by rounding off corners using the Chaikin algorithm.
auto snappedToGrid(double hSpacing, double vSpacing, double dSpacing = 0, double mSpacing = 0) const -> QgsGeometry
Returns a new geometry with all points or vertices snapped to the closest point of the grid.
auto splitGeometry(const QVector<QgsPointXY>& splitLine, QVector<QgsGeometry>& newGeometries, bool topological, QVector<QgsPointXY>& topologyTestPoints) -> OperationResult
Splits this geometry according to a given line.
auto sqrDistToVertexAt(QgsPointXY&point SIP_IN, int atVertex) const -> double
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))
auto subdivide(int maxNodes = 256) const -> QgsGeometry
Subdivides the geometry.
auto symDifference(const QgsGeometry& geometry) const -> QgsGeometry
Returns a geometry representing the points making up this geometry that do not make up other.
auto taperedBuffer(double startWidth, double endWidth, int segments) const -> QgsGeometry
Calculates a variable width buffer ("tapered buffer") for a (multi)curve geometry.
auto touches(const QgsGeometry& geometry) const -> bool
Test for if geometry touch another (uses GEOS)
auto transform(const QgsCoordinateTransform& ct, QgsCoordinateTransform::TransformDirection direction = QgsCoordinateTransform::ForwardTransform, bool transformZ = false) -> OperationResult
Transforms this geometry as described by the coordinate transform ct.
auto transform(const QTransform& t, double zTranslate = 0.0, double zScale = 1.0, double mTranslate = 0.0, double mScale = 1.0) -> OperationResult
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.
auto translate(double dx, double dy, double dz = 0.0, double dm = 0.0) -> OperationResult
Translates this geometry by dx, dy, dz and dm.
auto type() const -> QgsWkbTypes::GeometryType
Returns type of the geometry as a QgsWkbTypes::GeometryType.
void validateGeometry(QVector<QgsGeometry::Error>& errors, ValidationMethod method = ValidatorQgisInternal) const
Validates geometry and produces a list of geometry errors.
auto variableWidthBufferByM(int segments) const -> QgsGeometry
Calculates a variable width buffer for a (multi)linestring geometry, where the width at each node is taken from the linestring m values.
auto vertexAt(int atVertex) const -> QgsPoint
Returns coordinates of a vertex.
auto vertexIdFromVertexNr(int number, QgsVertexId& id) const -> bool
Calculates the vertex ID from a vertex number.
auto vertexNrFromVertexId(QgsVertexId id) const -> int
Returns the vertex number corresponding to a vertex id.
auto vertices() const -> QgsVertexIterator
Returns a read-only, Java-style iterator for traversal of vertices of all the geometry, including all geometry parts and rings.
auto vertices_begin() const -> QgsAbstractGeometry::vertex_iterator
Returns STL-style iterator pointing to the first vertex of the geometry.
auto vertices_end() const -> QgsAbstractGeometry::vertex_iterator
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
auto voronoiDiagram(const QgsGeometry& extent = QgsGeometry(), double tolerance = 0.0, bool edgesOnly = false) const -> QgsGeometry
Creates a Voronoi diagram for the nodes contained within the geometry.
auto within(const QgsGeometry& geometry) const -> bool
Test for if geometry is within another (uses GEOS)
auto wkbType() const -> QgsWkbTypes::Type
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)

Enum documentation

enum QgsGeometry::BufferSide

Side of line to buffer.

Enumerators
SideLeft

Buffer to left of line.

SideRight

Buffer to right of line.

enum QgsGeometry::EndCapStyle

End cap styles for buffers.

Enumerators
CapRound

Round cap.

CapFlat

Flat cap (in line with start/end of line)

CapSquare

Square cap (extends past start/end of line by buffer distance)

enum QgsGeometry::JoinStyle

Join styles for buffers.

Enumerators
JoinStyleRound

Use rounded joins.

JoinStyleMiter

Use mitered joins.

JoinStyleBevel

Use beveled joins.

enum QgsGeometry::OperationResult

Success or failure of a geometry operation.

This gives details about cause of failure.

Enumerators
Success

Operation succeeded.

NothingHappened

Nothing happened, without any error.

InvalidBaseGeometry

The base geometry on which the operation is done is invalid or empty.

InvalidInputGeometryType

The input geometry (ring, part, split line, etc.) has not the correct geometry type.

SelectionIsEmpty

No features were selected.

SelectionIsGreaterThanOne

More than one features were selected.

GeometryEngineError

Geometry engine misses a method implemented or an error occurred in the geometry engine.

LayerNotEditable

Cannot edit layer.

AddPartSelectedGeometryNotFound

The selected geometry cannot be found.

AddPartNotMultiGeometry

The source geometry is not multi.

AddRingNotClosed

The input ring is not closed.

AddRingNotValid

The input ring is not valid.

AddRingCrossesExistingRings

The input ring crosses existing rings (it is not disjoint)

AddRingNotInExistingFeature

The input ring doesn't have any existing ring to fit into.

SplitCannotSplitPoint

Cannot split points.

enum QgsGeometry::ValidationMethod

Available methods for validating geometries.

Enumerators
ValidatorQgisInternal

Use internal QgsGeometryValidator method.

ValidatorGeos

Use GEOS validation methods.

Function documentation

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

Compares two polylines for equality within a specified tolerance.

Parameters
p1 first polyline
p2 second polyline
epsilon maximum 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

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

Compares two polygons for equality within a specified tolerance.

Parameters
p1 first polygon
p2 second polygon
epsilon maximum 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

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

Compares two multipolygons for equality within a specified tolerance.

Parameters
p1 first multipolygon
p2 second multipolygon
epsilon maximum 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

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

Upgrades a point list from QgsPointXY to QgsPoint.

Parameters
input list of QgsPointXY objects to be upgraded
output destination for list of points converted to QgsPoint

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

Downgrades a point list from QgsPoint to QgsPointXY.

Parameters
input list of QgsPoint objects to be downgraded
output destination for list of points converted to QgsPointXY

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

Creates a QgsPolygonXYfrom a QPolygonF.

Parameters
polygon source polygon
Returns QgsPolygon

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

Creates a QgsPolylineXY from a QPolygonF.

Parameters
polygon source polygon
Returns QgsPolylineXY

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

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.

static QgsGeometry QgsGeometry::fromPolyline(const QgsPolyline& polyline)

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.

static QgsGeometry QgsGeometry::fromPolylineXY(const QgsPolylineXY& polyline)

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.

static QgsGeometry QgsGeometry::fromQPointF(QPointF point)

Construct geometry from a QPointF.

Parameters
point source QPointF

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

Construct geometry from a QPolygonF.

Parameters
polygon source 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.

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

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.

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

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.

QgsGeometry::QgsGeometry(QgsAbstractGeometry* geom) explicit

Creates a geometry from an abstract geometry object.

Ownership of geom is transferred.

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

Creates a geometry from an abstract geometry object.

Ownership of geom is transferred.

OperationResult QgsGeometry::addPart(const QVector<QgsPointXY>& points, QgsWkbTypes::GeometryType geomType = QgsWkbTypes::UnknownGeometry)

Adds a new part to a the geometry.

Parameters
points points describing part to add
geomType default geometry type to create if no existing geometry
Returns OperationResult a result code: success or reason of failure

OperationResult QgsGeometry::addPart(const QgsPointSequence& points, QgsWkbTypes::GeometryType geomType = QgsWkbTypes::UnknownGeometry)

Adds a new part to a the geometry.

Parameters
points points describing part to add
geomType default geometry type to create if no existing geometry
Returns OperationResult a result code: success or reason of failure

OperationResult QgsGeometry::addPart(QgsAbstractGeometry* part, QgsWkbTypes::GeometryType geomType = QgsWkbTypes::UnknownGeometry)

Adds a new part to this geometry.

Parameters
part part to add (ownership is transferred)
geomType default geometry type to create if no existing geometry
Returns OperationResult a result code: success or reason of failure

OperationResult QgsGeometry::addPart(const QgsGeometry& newPart)

Adds a new island polygon to a multipolygon feature.

Returns OperationResult a result code: success or reason of failure

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

Adds a new ring to this geometry.

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

This makes only sense for polygon and multipolygons.

OperationResult QgsGeometry::addRing(QgsCurve* ring)

Adds a new ring to this geometry.

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

This makes only sense for polygon and multipolygons.

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:

  1. If the given vertex index is at the end of a linestring, the adjacent index will be -1 (for "no adjacent vertex")
  2. 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).

double QgsGeometry::angleAtVertex(int vertex) const

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

Parameters
vertex vertex index to calculate bisector angle at
Returns bisector angle, in radians clockwise from north

double QgsGeometry::area() const

Returns the area of the geometry using GEOS.

QVector<QgsGeometry> QgsGeometry::asGeometryCollection() const

Returns contents of the geometry as a list of geometries.

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.

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.

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.

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.

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.

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.

QPointF QgsGeometry::asQPointF() const

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

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.

QByteArray QgsGeometry::asWkb() const

Export the geometry to WKB.

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

Exports the geometry to WKT.

Returns true in case of success and false else

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
avoidIntersectionsLayers list of layers to check for intersections
ignoreFeatures possibility 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 other error during intersection removal

QgsRectangle QgsGeometry::boundingBox() const

Returns the bounding box of the geometry.

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.

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.

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.

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

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

Parameters
distance buffer distance
segments for round joins, number of segments to approximate quarter-circle
endCapStyle end cap style
joinStyle join style for corners in geometry
miterLimit limit on the miter ratio used for very sharp corners (JoinStyleMiter only)

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 error() on the returned geometry.

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.

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

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

Parameters
point Specifies the point for search
minDistPoint Receives the nearest point on the segment
afterVertex Receives index of the vertex after the closest segment. The vertex before the closest segment is always afterVertex - 1
leftOf Out: Returns if the point lies on the left of left 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)
epsilon epsilon for segment snapping
Returns The squared Cartesian distance is also returned in sqrDist, negative number on error

QgsPointXY QgsGeometry::closestVertex(const QgsPointXY& point, int& atVertex, int& beforeVertex, int& afterVertex, 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
point point to search for
atVertex will be set to the vertex index of the closest found vertex
beforeVertex will be set to the vertex index of the previous vertex from the closest one. Will be set to -1 if not present.
afterVertex will be set to the vertex index of the next vertex after the closest one. Will be set to -1 if not present.
sqrDist will 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 nad sqrDist is negative.

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

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

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

QgsGeometry QgsGeometry::combine(const QgsGeometry& geometry) 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 error() on the returned geometry.

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.

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.

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.

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.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())
    
    # 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())

bool QgsGeometry::contains(const QgsGeometry& geometry) const

Tests for if geometry is contained in another (uses GEOS)

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

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

Returns true in case of success and false else

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.

bool QgsGeometry::convertToMultiType()

Converts single type geometry into multitype geometry e.g.

Returns true in case of success and false else

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.

bool QgsGeometry::convertToSingleType()

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

Returns true in case of success and false else

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.

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
tolerance segmentation tolerance
toleranceType maximum segmentation angle or maximum difference between approximation and curve

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

Try to convert the geometry to the requested type.

Parameters
destType the geometry type to be converted to
destMultipart determines if the output geometry will be multipart or not
Returns the converted geometry or nullptr if the conversion fails.

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 error() on the returned geometry.

bool QgsGeometry::crosses(const QgsGeometry& geometry) const

Test for if geometry crosses another (uses GEOS)

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.

bool QgsGeometry::deletePart(int partNum)

Deletes part identified by the part number.

Returns true on success

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

Deletes a ring in polygon or multipolygon.

Returns true on success

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

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?)

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.

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.

QgsGeometry QgsGeometry::difference(const QgsGeometry& geometry) 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 error() on the returned geometry.

bool QgsGeometry::disjoint(const QgsGeometry& geometry) const

Tests for if geometry is disjoint of another (uses GEOS)

double QgsGeometry::distance(const QgsGeometry& geom) const

Returns the minimum distance between this geometry and another geometry, using GEOS.

Parameters
geom geometry to find minimum distance to

Will return a negative value if a geometry is missing.

double QgsGeometry::distanceToVertex(int vertex) const

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

Parameters
vertex vertex index to calculate distance to
Returns distance to vertex (following geometry), or -1 for invalid vertex numbers

void QgsGeometry::draw(QPainter& p) const

Draws the geometry onto a QPainter.

Parameters
p destination QPainter

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().

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.

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.

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.

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.

void QgsGeometry::fromWkb(const QByteArray& wkb)

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

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.

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.

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.

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?)

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?)

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.

double QgsGeometry::interpolateAngle(double distance) const

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

Parameters
distance distance along 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.

QgsGeometry QgsGeometry::intersection(const QgsGeometry& geometry) 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 error() on the returned geometry.

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.

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.

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().

bool QgsGeometry::isGeosEqual(const QgsGeometry&) 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.

bool QgsGeometry::isGeosValid() const

Checks validity of the geometry using GEOS.

Q_INVOKABLE bool QgsGeometry::isNull() const

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

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.

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.

double QgsGeometry::length() const

Returns the length of geometry using GEOS.

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.

Parameters
point point to seek proximity to
Returns distance along line, or -1 on error

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.

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
other geometry that should not be intersect
Returns difference geometry, or empty geometry if difference could not be calculated

int QgsGeometry::makeDifferenceInPlace(const QgsGeometry& other)

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

Parameters
other geometry that should not be intersect

QgsGeometry QgsGeometry::makeValid() const

Attempts to make an invalid geometry valid without losing vertices.

Returns new valid QgsGeometry or null geometry on error

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 error() on the returned geometry.

void QgsGeometry::mapToPixel(const QgsMapToPixel& mtp)

Transforms the geometry from map units to pixels in place.

Parameters
mtp map to pixel transform

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.

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

Returns the minimal enclosing circle for the geometry.

Parameters
center Center of the minimal enclosing circle returneds
radius Radius of the minimal enclosing circle returned
segments Number of segments used to segment geometry.
Returns the minimal enclosing circle as a QGIS geometry

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

Returns the minimal enclosing circle for the geometry.

Parameters
segments Number of segments used to segment geometry.

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

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

QgsGeometry QgsGeometry::nearestPoint(const QgsGeometry& other) const

Returns the nearest point on this geometry to another geometry.

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

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

Parameters
distance buffer distance
segments for round joins, number of segments to approximate quarter-circle
joinStyle join style for corners in geometry
miterLimit limit on the miter ratio used for very sharp corners (JoinStyleMiter only)

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

Creates a deep copy of the object.

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.

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.

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.

bool QgsGeometry::overlaps(const QgsGeometry& geometry) const

Test for if geometry overlaps another (uses GEOS)

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())

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.

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.

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 error() on the returned geometry.

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.

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.

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.

bool QgsGeometry::requiresConversionToStraightSegments() const

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

OperationResult QgsGeometry::reshapeGeometry(const QgsLineString& reshapeLineString)

Replaces a part of this geometry with another line.

Returns OperationResult a result code: success or reason of failure

OperationResult QgsGeometry::rotate(double rotation, const QgsPointXY& center)

Rotate this geometry around the Z axis.

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

void QgsGeometry::set(QgsAbstractGeometry* geometry)

Sets the underlying geometry store.

Ownership of geometry is transferred.

QgsGeometry QgsGeometry::shortestLine(const QgsGeometry& other) const

Returns the shortest line joining this geometry to another geometry.

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

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

Parameters
distance buffer distance
segments for round joins, number of segments to approximate quarter-circle
side side of geometry to buffer
joinStyle join style for corners
miterLimit limit on the miter ratio used for very sharp corners
Returns buffered geometry, or an empty geometry if buffer could not be calculated

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

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.

Parameters
iterations number of smoothing iterations to run. More iterations results in a smoother geometry
offset fraction 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.
minimumDistance minimum segment length to apply smoothing to
maxAngle maximum angle at node (0-180) at which smoothing will be applied

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.

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.

Parameters
hSpacing Horizontal spacing of the grid (x axis). 0 to disable.
vSpacing Vertical spacing of the grid (y axis). 0 to disable.
dSpacing Depth spacing of the grid (z axis). 0 (default) to disable.
mSpacing Custom dimension spacing of the grid (m axis). 0 (default) to disable.

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.

OperationResult QgsGeometry::splitGeometry(const QVector<QgsPointXY>& splitLine, QVector<QgsGeometry>& newGeometries, bool topological, QVector<QgsPointXY>& topologyTestPoints)

Splits this geometry according to a given line.

Parameters
splitLine the line that splits the geometry
newGeometries out list of new geometries that have been created with the split
topological true if topological editing is enabled
topologyTestPoints out points that need to be tested for topological completeness in the dataset
Returns OperationResult a result code: success or reason of failure

QgsGeometry QgsGeometry::subdivide(int maxNodes = 256) 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 error() on the returned geometry.

QgsGeometry QgsGeometry::symDifference(const QgsGeometry& geometry) 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 error() on the returned geometry.

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.

bool QgsGeometry::touches(const QgsGeometry& geometry) const

Test for if geometry touch another (uses GEOS)

OperationResult QgsGeometry::transform(const QgsCoordinateTransform& ct, QgsCoordinateTransform::TransformDirection direction = QgsCoordinateTransform::ForwardTransform, bool transformZ = false)

Transforms this geometry as described by the coordinate transform ct.

Returns OperationResult a result code: success or reason of failure

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).

OperationResult 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.

Returns OperationResult a result code: success or reason of failure

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.

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.

OperationResult 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

QgsWkbTypes::GeometryType QgsGeometry::type() const

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

void QgsGeometry::validateGeometry(QVector<QgsGeometry::Error>& errors, ValidationMethod method = ValidatorQgisInternal) const

Validates geometry and produces a list of geometry errors.

The method argument dictates which validator to utilize.

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.

QgsPoint QgsGeometry::vertexAt(int atVertex) const

Returns coordinates of a vertex.

Parameters
atVertex index of the vertex
Returns Coordinates of the vertex or QgsPoint(0,0) on error

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.

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.

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.

  • 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())

QgsAbstractGeometry::vertex_iterator QgsGeometry::vertices_begin() const

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

QgsAbstractGeometry::vertex_iterator QgsGeometry::vertices_end() const

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

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.

bool QgsGeometry::within(const QgsGeometry& geometry) const

Test for if geometry is within another (uses GEOS)

QgsWkbTypes::Type QgsGeometry::wkbType() const

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