Class: QgsGeometry¶
- class qgis.core.QgsGeometry¶
Bases:
sip.wrapper
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 theget()
method or set using theset()
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 theQgsGeometry
API (orQgsAbstractGeometry
subclasses) utilize geodesic calculations. Accordingly, properties likelength()
andarea()
or spatial operations likebuffer()
are always calculated using strictly Cartesian mathematics. In contrast, theQgsDistanceArea
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.QgsGeometry() Constructor
QgsGeometry(
QgsGeometry
) Copy constructor will prompt a deep copy of the objectQgsGeometry(geom:
QgsAbstractGeometry
) Creates a geometry from an abstract geometry object. Ownership of geom is transferred.New in version 2.10:
Enums
Bases:
enum.IntEnum
Bases:
enum.IntEnum
Bases:
enum.IntEnum
alias of
GeometryOperationResult
alias of
GeometryValidationEngine
alias of
GeometryValidityFlag
Methods
Adds a new part to this geometry.
Adds a new island polygon to a multipolygon feature
Adds a new part to a the geometry.
Adds a new part to a the geometry.
Adds a new ring to this geometry.
Returns the indexes of the vertices before and after the given vertex index.
Returns the bisector angle for this geometry at the specified vertex.
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
.Returns the planar, 2-dimensional area of the geometry.
Returns contents of the geometry as a list of geometries
Exports the geometry to a GeoJSON string.
Returns the contents of the geometry as a multi-point.
Returns the contents of the geometry as a multi-polygon.
Returns the contents of the geometry as a multi-linestring.
Returns the contents of the geometry as a 2-dimensional point.
Returns the contents of the geometry as a polygon.
Returns the contents of the geometry as a polyline.
Returns contents of the geometry as a QPointF if wkbType is WKBPoint, otherwise returns a null QPointF.
Returns contents of the geometry as a QPolygonF.
Export the geometry to WKB
Exports the geometry to WKT
Modifies geometry to avoid intersections with the layers specified in project properties
Modifies geometry to avoid intersections with the layers specified in project properties
Returns the bounding box of the geometry.
Returns the 3D bounding box of the geometry.
Returns
True
if the bounding box of this geometry intersects with arectangle
.Returns a buffer region around this geometry having the given width and with a specified number of segments used to approximate curves
Returns the center of mass of a geometry.
Clips the geometry using the specified
rectangle
.Searches for the closest segment of geometry to the given point
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.
Searches for the closest vertex in this geometry to the given point.
Attempts to coerce this geometry into the specified destination
type
.Creates a new multipart geometry from a list of
QgsGeometry
objectsReturns a geometry representing all the points in this geometry and other (a union geometry operation).
Compares two geometry objects for equality within a specified tolerance.
Returns a possibly concave polygon that contains all the points in the geometry.
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Returns Java-style iterator for traversal of parts of the geometry.
Returns
True
if the geometry contains the pointp
.Converts geometry collection to a the desired geometry type subclass (multi-point, multi-linestring or multi-polygon).
Upgrades a point list from
QgsPointXY
toQgsPoint
Converts a geometry into a multitype geometry of curve kind (when there is a corresponding curve type).
Attempts to convert a non-curved geometry into a curved geometry type (e.g. LineString to CompoundCurve, Polygon to CurvePolygon).
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.Converts multi type geometry into single type geometry e.g. a multipolygon into a polygon geometry.
Converts the geometry to straight line segments, if it is a curved geometry type.
Try to convert the geometry to the requested type
Returns the smallest convex polygon that contains all the points in the geometry.
Creates and returns a new geometry engine representing the specified
geometry
.Creates a
QgsPolygonXYfrom
a QPolygonF.Creates a
QgsPolylineXY
from a QPolygonF.Creates a wedge shaped buffer from a
center
point.Returns
True
if the geometry crosses anothergeometry
.Returns the Delaunay triangulation for the vertices of the geometry.
Deletes part identified by the part number
Deletes a ring in polygon or multipolygon.
Deletes the vertex at the given position number and item (first number is index 0)
Returns a copy of the geometry which has been densified by adding the specified number of extra nodes within each segment of the geometry.
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
.Returns a geometry representing the points making up this geometry that do not make up other.
Returns
True
if the geometry is disjoint of anothergeometry
.Returns the minimum distance between this geometry and another geometry.
Returns the distance along this geometry from its first vertex to the specified vertex.
Draws the geometry onto a QPainter
Test if this geometry is exactly equal to another
geometry
.Extends a (multi)line geometry by extrapolating out the start or end of the line by a specified distance.
Returns an extruded version of this geometry.
Forces geometries to respect the exterior ring is clockwise, interior rings are counter-clockwise convention.
Forces geometries to respect the exterior ring is counter-clockwise, interior rings are clockwise convention.
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.
Returns the Fréchet distance between this geometry and
geom
, restricted to discrete points for both geometries.Returns the Fréchet distance between this geometry and
geom
, restricted to discrete points for both geometries.Creates a new geometry from a
QgsBox3D
objectCreates a new geometry from a
QgsMultiPointXY
objectCreates a new geometry from a
QgsMultiPolygonXY
.Creates a new geometry from a
QgsMultiPolylineXY
object.Creates a new geometry from a
QgsPoint
object.Creates a new geometry from a
QgsPointXY
objectCreates a new polygon geometry from a list of lists of
QgsPointXY
.Creates a new LineString geometry from a list of
QgsPoint
points.Creates a new LineString geometry from a list of
QgsPointXY
points.Construct geometry from a QPointF
Construct geometry from a QPolygonF.
Creates a new geometry from a
QgsRectangle
Set the geometry, feeding in the buffer containing OGC Well-Known Binary
Creates a new geometry from a WKT string
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
Returns the Hausdorff distance between this geometry and
geom
.Returns the Hausdorff distance between this geometry and
geom
.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 an interpolated point on the geometry at the specified
distance
.Returns the angle parallel to the linestring or polygon boundary at the specified distance along the geometry.
Returns a geometry representing the points shared by this geometry and other.
Returns
True
if this geometry exactly intersects with arectangle
.Returns
True
if the geometry is a polygon that is almost an axis-parallel rectangle.Returns
True
if the geometry is empty (eg a linestring with no vertices, or a collection with no geometries).Compares the geometry with another geometry using GEOS.
Checks validity of the geometry using GEOS.
Returns
True
if WKB of the geometry is of WKBMulti* typeReturns
True
if the geometry is null (ie, contains no underlying geometry accessible viaget()
orconstGet()
).Returns True if the Polygon is clockwise.
Returns True if the Polygon is counter-clockwise.
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.
Constructs the Largest Empty Circle for a set of obstacle geometries, up to a specified tolerance.
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.
Returns the planar, 2-dimensional length of geometry.
Returns a distance representing the location along this linestring of the closest point on this linestring geometry to the specified point.
Returns the geometry formed by modifying this geometry such that it does not intersect the other geometry.
Attempts to make an invalid geometry valid without losing vertices.
Transforms the geometry from map units to pixels in place.
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line strings.
Returns the minimal enclosing circle for the geometry.
Computes the minimum clearance of a geometry.
Returns a LineString whose endpoints define the minimum clearance of a geometry.
Returns a linestring geometry which represents the minimum diameter of the geometry.
Moves the vertex at the given position number and item (first number is index 0) to the given coordinates.
Returns the nearest (closest) point on this geometry to another geometry.
Returns a (Multi)LineString representing the fully noded version of a collection of linestrings.
Reorganizes the geometry into a normalized form (or "canonical" form).
Returns an offset line at a given distance and side from an input line.
Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated rectangle which fully encompasses the geometry.
Attempts to orthogonalize a line or polygon geometry by shifting vertices to make the geometries angles either right angles or flat lines.
Returns
True
if the geometry overlaps anothergeometry
.Returns Java-style iterator for traversal of parts of the geometry.
Returns a point guaranteed to lie on the surface of a geometry.
Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal point from the boundary of the surface.
Returns the orientation of the polygon.
Creates a GeometryCollection geometry containing possible polygons formed from the constituent linework of a set of
geometries
.Returns a list of
count
random points generated inside a (multi)polygon geometry.Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerate geometry.
Removes the interior rings from a (multi)polygon geometry.
Returns
True
if the geometry is a curved geometry type which requires conversion to display as straight line segments.Replaces a part of this geometry with another line
Rotate this geometry around the Z axis
Constructs rounded (sine-like) waves along the boundary of the geometry, with the specified
wavelength
andamplitude
.Constructs randomized rounded (sine-like) waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
Sets the underlying geometry store.
Find paths shared between the two given lineal geometries (this and
other
).Returns the shortest line joining this geometry to another geometry.
Returns a simplified version of this geometry using a specified tolerance value
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).
Returns a single sided buffer for a (multi)line geometry.
Smooths a geometry by rounding off corners using the Chaikin algorithm.
Returns a new geometry with all points or vertices snapped to the closest point of the grid.
Splits this geometry according to a given line.
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))
Constructs square waves along the boundary of the geometry, with the specified
wavelength
andamplitude
.Constructs randomized square waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
Subdivides the geometry.
Returns a geometry representing the points making up this geometry that do not make up other.
Calculates a variable width buffer ("tapered buffer") for a (multi)curve geometry.
Converts the vertex at the given position from/to circular
Returns
True
if the geometry touches anothergeometry
.Transforms this geometry as described by the coordinate transform
ct
.Translates this geometry by dx, dy, dz and dm.
Constructs triangular waves along the boundary of the geometry, with the specified
wavelength
andamplitude
.Constructs randomized triangular waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
Returns type of the geometry as a
Qgis
.GeometryTypeCompute the unary union on a list of
geometries
.Optimized union algorithm for polygonal inputs that are correctly noded and do not overlap.
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.
Validates geometry and produces a list of geometry errors.
Calculates a variable width buffer for a (multi)linestring geometry, where the width at each node is taken from the linestring m values.
Returns coordinates of a vertex.
Calculates the vertex ID from a vertex
number
.Returns the vertex number corresponding to a vertex
id
.Returns a read-only, Java-style iterator for traversal of vertices of all the geometry, including all geometry parts and rings.
Creates a Voronoi diagram for the nodes contained within the geometry.
Returns
True
if the geometry is completely within anothergeometry
.Returns the length of the QByteArray returned by
asWkb()
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
Attributes
- class BufferSide(value)¶
Bases:
enum.IntEnum
Side of line to buffer.
New in version 3.22.
SideLeft
: Buffer to left of lineSideRight
: Buffer to right of line
- class EndCapStyle(value)¶
Bases:
enum.IntEnum
End cap styles for buffers.
New in version 3.22.
CapRound
: Round capCapFlat
: Flat cap (in line with start/end of line)CapSquare
: Square cap (extends past start/end of line by buffer distance)
- class Error¶
Bases:
sip.wrapper
A geometry error.
- what(self) str ¶
A human readable error message containing details about the error.
- Return type:
str
- where(self) QgsPointXY ¶
The coordinates at which the error is located and should be visualized.
- Return type:
- class JoinStyle(value)¶
Bases:
enum.IntEnum
Join styles for buffers.
New in version 3.22.
JoinStyleRound
: Use rounded joinsJoinStyleMiter
: Use mitered joinsJoinStyleBevel
: Use beveled joins
- OperationResult¶
alias of
GeometryOperationResult
- ValidationMethod¶
alias of
GeometryValidationEngine
- ValidityFlag¶
alias of
GeometryValidityFlag
- ValidityFlags¶
alias of
GeometryValidityFlags
- addPart(self, part: QgsAbstractGeometry, geomType: Qgis.GeometryType = Qgis.GeometryType.Unknown) Qgis.GeometryOperationResult ¶
Adds a new part to this geometry.
- Parameters:
part (QgsAbstractGeometry) – part to add (ownership is transferred)
geomType (Qgis.GeometryType = Qgis.GeometryType.Unknown) – default geometry type to create if no existing geometry
- Return type:
- Returns:
OperationResult a result code: success or reason of failure
- addPartGeometry(self, newPart: QgsGeometry) Qgis.GeometryOperationResult ¶
Adds a new island polygon to a multipolygon feature
- Return type:
- Returns:
OperationResult a result code: success or reason of failure
Note
available in python bindings as addPartGeometry
- Parameters:
newPart (QgsGeometry) –
- addPoints(self, points: Iterable[QgsPoint], geomType: Qgis.GeometryType = Qgis.GeometryType.Unknown) Qgis.GeometryOperationResult ¶
Adds a new part to a the geometry.
- Parameters:
points (Iterable[QgsPoint]) – points describing part to add
geomType (Qgis.GeometryType = Qgis.GeometryType.Unknown) – default geometry type to create if no existing geometry
- Return type:
- Returns:
OperationResult a result code: success or reason of failure
- addPointsXY(self, points: Iterable[QgsPointXY], geomType: Qgis.GeometryType = Qgis.GeometryType.Unknown) Qgis.GeometryOperationResult ¶
Adds a new part to a the geometry.
- Parameters:
points (Iterable[QgsPointXY]) – points describing part to add
geomType (Qgis.GeometryType = Qgis.GeometryType.Unknown) – default geometry type to create if no existing geometry
- Return type:
- Returns:
OperationResult a result code: success or reason of failure
- addRing(self, ring: Iterable[QgsPointXY]) Qgis.GeometryOperationResult ¶
Adds a new ring to this geometry. This makes only sense for polygon and multipolygons.
- Parameters:
ring (Iterable[QgsPointXY]) – The ring to be added
- Returns:
OperationResult a result code: success or reason of failure
addRing(self, ring:
QgsCurve
) -> Qgis.GeometryOperationResult Adds a new ring to this geometry. This makes only sense for polygon and multipolygons.- Parameters:
ring – The ring to be added
- Return type:
- Returns:
OperationResult a result code: success or reason of failure
- adjacentVertices(self, atVertex: int) Tuple[int, int] ¶
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).
- Parameters:
atVertex (int) –
- Return type:
Tuple[int, int]
- angleAtVertex(self, vertex: int) float ¶
Returns the bisector angle for this geometry at the specified vertex.
- Parameters:
vertex (int) – vertex index to calculate bisector angle at
- Return type:
float
- Returns:
bisector angle, in radians clockwise from north
See also
New in version 3.0.
- applyDashPattern(self, pattern: Iterable[float], startRule: Qgis.DashPatternLineEndingRule = Qgis.DashPatternLineEndingRule.NoRule, endRule: Qgis.DashPatternLineEndingRule = Qgis.DashPatternLineEndingRule.NoRule, adjustment: Qgis.DashPatternSizeAdjustment = Qgis.DashPatternSizeAdjustment.ScaleBothDashAndGap, patternOffset: float = 0) QgsGeometry ¶
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
andendRule
options can be set to control how the dash pattern is adjusted at line endings. If astartRule
orendRule
is set, theadjustment
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.New in version 3.24.
- Parameters:
pattern (Iterable[float]) –
startRule (Qgis.DashPatternLineEndingRule = Qgis.DashPatternLineEndingRule.NoRule) –
endRule (Qgis.DashPatternLineEndingRule = Qgis.DashPatternLineEndingRule.NoRule) –
adjustment (Qgis.DashPatternSizeAdjustment = Qgis.DashPatternSizeAdjustment.ScaleBothDashAndGap) –
patternOffset (float = 0) –
- Return type:
- area(self) float ¶
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, theQgsDistanceArea
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
New in version 1.5.
- Return type:
float
- asGeometryCollection(self) List[QgsGeometry] ¶
Returns contents of the geometry as a list of geometries
New in version 1.1.
- Return type:
List[QgsGeometry]
- asJson(self, precision: int = 17) str ¶
Exports the geometry to a GeoJSON string.
- Parameters:
precision (int = 17) –
- Return type:
str
- asMultiPoint(self) QgsMultiPointXY ¶
Returns the contents of the geometry as a multi-point.
Any z or m values present in the geometry will be discarded.
This method works only with multi-point geometry types.
- Raises:
TypeError – if the geometry is not a multi-point type
ValueError – if the geometry is null
- Return type:
QgsMultiPointXY
- asMultiPolygon(self) QgsMultiPolygonXY ¶
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.
This method works only with multi-polygon (or multi-curve polygon) geometry types.
- Raises:
TypeError – if the geometry is not a multi-polygon type
ValueError – if the geometry is null
- Return type:
QgsMultiPolygonXY
- asMultiPolyline(self) QgsMultiPolylineXY ¶
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.
This method works only with multi-linestring (or multi-curve) geometry types.
- Raises:
TypeError – if the geometry is not a multi-linestring type
ValueError – if the geometry is null
- Return type:
QgsMultiPolylineXY
- asPoint(self) QgsPointXY ¶
Returns the contents of the geometry as a 2-dimensional point.
Any z or m values present in the geometry will be discarded.
This method works only with single-point geometry types.
- Raises:
TypeError – if the geometry is not a single-point type (or a multipoint containing a single point)
ValueError – if the geometry is null
- Return type:
- asPolygon(self) QgsPolygonXY ¶
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.
This method works only with single-polygon (or single-curve polygon) geometry types.
- Raises:
TypeError – if the geometry is not a single-polygon type
ValueError – if the geometry is null
- Return type:
QgsPolygonXY
- asPolyline(self) QgsPolylineXY ¶
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.
This method works only with single-line (or single-curve).
- Raises:
TypeError – if the geometry is not a single-line type
ValueError – if the geometry is null
- Return type:
QgsPolylineXY
- asQPointF(self) QPointF ¶
Returns contents of the geometry as a QPointF if wkbType is WKBPoint, otherwise returns a null QPointF.
New in version 2.7.
- Return type:
QPointF
- asQPolygonF(self) QPolygonF ¶
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.
New in version 2.7.
- Return type:
QPolygonF
- asWkb(self, flags: QgsAbstractGeometry.WkbFlags | QgsAbstractGeometry.WkbFlag = QgsAbstractGeometry.WkbFlags()) QByteArray ¶
Export the geometry to WKB
The optional
flags
argument specifies flags controlling WKB export behavior (since QGIS 3.14).New in version 3.0.
- Parameters:
flags (Union[QgsAbstractGeometry.WkbFlags) –
- Return type:
QByteArray
- asWkt(self, precision: int = 17) str ¶
Exports the geometry to WKT
- Return type:
str
- Returns:
True
in case of success andFalse
else
Note
precision parameter added in QGIS 2.4
- Parameters:
precision (int = 17) –
- avoidIntersections(self, avoidIntersectionsLayers: Iterable[QgsVectorLayer]) int ¶
Modifies geometry to avoid intersections with the layers specified in project properties
- Parameters:
avoidIntersectionsLayers (Iterable[QgsVectorLayer]) – list of layers to check for intersections
- Return type:
int
- 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.
New in version 1.5.
Deprecated since version QGIS: 3.34
- avoidIntersectionsV2(self, avoidIntersectionsLayers: Iterable[QgsVectorLayer]) Qgis.GeometryOperationResult ¶
Modifies geometry to avoid intersections with the layers specified in project properties
- Parameters:
avoidIntersectionsLayers (Iterable[QgsVectorLayer]) – list of layers to check for intersections
- Return type:
- 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.
New in version 3.34.
- boundingBox(self) QgsRectangle ¶
Returns the bounding box of the geometry.
See also
- Return type:
- boundingBox3D(self) QgsBox3D ¶
Returns the 3D bounding box of the geometry.
New in version 3.34.
- Return type:
- boundingBoxIntersects(self, rectangle: QgsRectangle) bool ¶
Returns
True
if the bounding box of this geometry intersects with arectangle
. Since this test only considers the bounding box of the geometry, is is very fast to calculate and handles invalid geometries.See also
New in version 3.0.
boundingBoxIntersects(self, geometry:
QgsGeometry
) -> bool ReturnsTrue
if the bounding box of this geometry intersects with the bounding box of anothergeometry
. Since this test only considers the bounding box of the geometries, is is very fast to calculate and handles invalid geometries.See also
New in version 3.0.
- Parameters:
rectangle (QgsRectangle) –
- Return type:
bool
- buffer(self, distance: float, segments: int) QgsGeometry ¶
Returns a buffer region around this geometry having the given width and with a specified number of segments used to approximate curves
See also
See also
buffer(self, distance: float, segments: int, endCapStyle: Qgis.EndCapStyle, joinStyle: Qgis.JoinStyle, miterLimit: float) -> QgsGeometry Returns a buffer region around the geometry, with additional style options.
- Parameters:
distance (float) – buffer distance
segments (int) – 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)
See also
See also
New in version 2.4.
- Return type:
- centroid(self) QgsGeometry ¶
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
See also
- Return type:
- clipped(self, rectangle: QgsRectangle) QgsGeometry ¶
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.New in version 3.0.
- Parameters:
rectangle (QgsRectangle) –
- Return type:
- closestSegmentWithContext(self, point: QgsPointXY, epsilon: float = DEFAULT_SEGMENT_EPSILON) Tuple[float, QgsPointXY, int, int] ¶
Searches for the closest segment of geometry to the given point
- Parameters:
point (QgsPointXY) – Specifies the point for search
epsilon (float = DEFAULT_SEGMENT_EPSILON) – epsilon for segment snapping
- Return type:
Tuple[float,
QgsPointXY
, int, int]- Returns:
The squared Cartesian distance is also returned in sqrDist, negative number on error
minDistPoint: Receives the nearest point on the segment
nextVertexIndex: Receives index of the next vertex after the closest segment. The vertex before the closest segment is always nextVertexIndex - 1
leftOrRightOfSegment: Out: 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)
- closestVertex(self, point: QgsPointXY) Tuple[QgsPointXY, int, int, int, float] ¶
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 (QgsPointXY) – point to search for
- Return type:
Tuple[
QgsPointXY
, int, int, int, float]- Returns:
closest point in geometry. If not found (empty geometry), returns null point and sqrDist is negative.
closestVertexIndex: will be set to the vertex index of the closest found vertex
previousVertexIndex: will be set to the vertex index of the previous vertex from the closest one. Will be set to -1 if not present.
nextVertexIndex: 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
- closestVertexWithContext(self, point: QgsPointXY) Tuple[float, int] ¶
Searches for the closest vertex in this geometry to the given point.
- Parameters:
point (QgsPointXY) – Specifiest the point for search
- Return type:
Tuple[float, int]
- Returns:
The squared Cartesian distance is also returned in sqrDist, negative number on error
atVertex: Receives index of the closest vertex
- coerceToType(self, type: Qgis.WkbType, defaultZ: float = 0, defaultM: float = 0) List[QgsGeometry] ¶
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 typecurved 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
anddefaultM
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 desiredtype
. It also correctly maintains curves and z/m values wherever appropriate.New in version 3.14.
- Parameters:
type (Qgis.WkbType) –
defaultZ (float = 0) –
defaultM (float = 0) –
- Return type:
List[QgsGeometry]
- collectGeometry(geometries: Iterable[QgsGeometry]) QgsGeometry ¶
Creates a new multipart geometry from a list of
QgsGeometry
objects- Parameters:
geometries (Iterable[QgsGeometry]) –
- Return type:
- combine(self, geometry: QgsGeometry, parameters: QgsGeometryParameters = QgsGeometryParameters()) QgsGeometry ¶
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.- Parameters:
geometry (QgsGeometry) –
parameters (
QgsGeometryParameters
= QgsGeometryParameters()) –
- Return type:
- compare(obj1: object, obj2: object, epsilon: float = 4 * DBL_EPSILON) bool ¶
Compares two geometry objects for equality within a specified tolerance. The objects can be of type
QgsPolylineXY
,QgsPolygonXYor
QgsMultiPolygon
. The 2 types should match.- Parameters:
p1 – first geometry object
p2 – second geometry object
epsilon (float = 4*DBL_EPSILON) – maximum difference for coordinates between the objects
- Return type:
bool
- Returns:
True
if objects arepolylines and have the same number of points and all points are equal within the specified tolerance
polygons and have the same number of points and all points are equal within the specified tolerance
multipolygons and 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
New in version 2.9.
- Parameters:
obj1 (object) –
obj2 (object) –
- concaveHull(self, targetPercent: float, allowHoles: bool = False) QgsGeometry ¶
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.- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.10 or earlier.
New in version 3.28.
- Parameters:
targetPercent (float) –
allowHoles (bool = False) –
- Return type:
- constGet(self) QgsAbstractGeometry ¶
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
See also
New in version 3.0.
- Return type:
- constParts(self) QgsGeometryConstPartIterator ¶
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())
See also
See also
New in version 3.6.
- rtype:
QgsGeometryConstPartIterator
- contains(self, p: QgsPointXY) bool ¶
Returns
True
if the geometry contains the pointp
.contains(self, geometry:
QgsGeometry
) -> bool ReturnsTrue
if the geometry completely contains anothergeometry
.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 callingcontains()
directly. SeecreateGeometryEngine()
for details on how to use theQgsGeometryEngine
class.New in version 1.5.
- Parameters:
p (QgsPointXY) –
- Return type:
bool
- convertGeometryCollectionToSubclass(self, geomType: Qgis.GeometryType) bool ¶
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.
- Return type:
bool
- Returns:
True
in case of success andFalse
else
New in version 3.2.
- Parameters:
geomType (Qgis.GeometryType) –
- convertPointList(input: Iterable[QgsPointXY], output: Iterable[QgsPoint])¶
Upgrades a point list from
QgsPointXY
toQgsPoint
- Parameters:
input (Iterable[QgsPointXY]) – list of
QgsPointXY
objects to be upgradedoutput (Iterable[QgsPoint]) – destination for list of points converted to
QgsPoint
convertPointList(input: Iterable[QgsPoint], output: Iterable[QgsPointXY]) Downgrades a point list from
QgsPoint
toQgsPointXY
- Parameters:
input – list of
QgsPoint
objects to be downgradedoutput – destination for list of points converted to
QgsPointXY
- convertToCurvedMultiType(self) bool ¶
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 returnTrue
and do nothing if the current geometry is a multipoint or a geometry collection. A single point will be transformed to a multipoint.- Return type:
bool
- Returns:
True
in case of success andFalse
else
New in version 3.30.
- convertToCurves(self, distanceTolerance: float = 1e-08, angleTolerance: float = 1e-08) QgsGeometry ¶
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
New in version 3.14.
- Parameters:
distanceTolerance (float = 1e-08) –
angleTolerance (float = 1e-08) –
- Return type:
- convertToMultiType(self) bool ¶
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.- Return type:
bool
- Returns:
True
in case of success andFalse
else
- convertToSingleType(self) bool ¶
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.- Return type:
bool
- Returns:
True
in case of success andFalse
else
- convertToStraightSegment(self, tolerance: float = M_PI / 180, toleranceType: QgsAbstractGeometry.SegmentationToleranceType = QgsAbstractGeometry.MaximumAngle)¶
Converts the geometry to straight line segments, if it is a curved geometry type.
- Parameters:
tolerance (float = M_PI/180) – segmentation tolerance
toleranceType (QgsAbstractGeometry.SegmentationToleranceType = QgsAbstractGeometry.MaximumAngle) – maximum segmentation angle or maximum difference between approximation and curve
New in version 2.10.
- convertToType(self, destType: Qgis.GeometryType, destMultipart: bool = False) QgsGeometry ¶
Try to convert the geometry to the requested type
- Parameters:
destType (Qgis.GeometryType) – the geometry type to be converted to
destMultipart (bool = False) – determines if the output geometry will be multipart or not
- Return type:
- Returns:
the converted geometry or
None
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.New in version 2.2.
- convexHull(self) QgsGeometry ¶
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.- Return type:
- createGeometryEngine(geometry: QgsAbstractGeometry) QgsGeometryEngine ¶
Creates and returns a new geometry engine representing the specified
geometry
.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 equivalentQgsGeometry
methods such asQgsGeometry.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 callingintersects()
,within()
, etc) then the geometry should first be prepared by callingprepareGeometry()
before performing the tests.Example¶
# polygon_geometry contains a complex polygon, with many vertices polygon_geometry = QgsGeometry.fromWkt('Polygon((...))') # create a :py:class:`.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!')
QgsGeometryEngine
operations are backed by the GEOS library (https://trac.osgeo.org/geos/).- param geometry:
- type geometry:
QgsAbstractGeometry
- rtype:
QgsGeometryEngine
- createPolygonFromQPolygonF(polygon: QPolygonF) object ¶
Creates a
QgsPolygonXYfrom
a QPolygonF.- Parameters:
polygon (QPolygonF) – source polygon
- Return type:
object
- Returns:
See also
Deprecated since version use:
QgsGeometry.fromQPolygonF()
orQgsLineString.fromQPolygonF()
instead.
- createPolylineFromQPolygonF(polygon: QPolygonF) List[QgsPointXY] ¶
Creates a
QgsPolylineXY
from a QPolygonF.- Parameters:
polygon (QPolygonF) – source polygon
- Return type:
List[QgsPointXY]
- Returns:
QgsPolylineXY
See also
Deprecated since version use:
QgsGeometry.fromQPolygonF()
orQgsLineString.fromQPolygonF()
instead.
- createWedgeBuffer(center: QgsPoint, azimuth: float, angularWidth: float, outerRadius: float, innerRadius: float = 0) QgsGeometry ¶
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 theangularWidth
parameter. Note that the wedge will extend to half of theangularWidth
either side of theazimuth
direction.The outer radius of the buffer is specified via
outerRadius
, and optionally aninnerRadius
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.
New in version 3.2.
- Parameters:
center (QgsPoint) –
azimuth (float) –
angularWidth (float) –
outerRadius (float) –
innerRadius (float = 0) –
- Return type:
- crosses(self, geometry: QgsGeometry) bool ¶
Returns
True
if the geometry crosses anothergeometry
.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 callingcrosses()
directly. SeecreateGeometryEngine()
for details on how to use theQgsGeometryEngine
class.New in version 1.5.
- Parameters:
geometry (QgsGeometry) –
- Return type:
bool
- delaunayTriangulation(self, tolerance: float = 0, edgesOnly: bool = False) QgsGeometry ¶
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. IfedgesOnly
isTrue
than line string boundary geometries will be returned instead of polygons. An empty geometry will be returned if the diagram could not be calculated.New in version 3.0.
- Parameters:
tolerance (float = 0) –
edgesOnly (bool = False) –
- Return type:
- deletePart(self, partNum: int) bool ¶
Deletes part identified by the part number
- Return type:
bool
- Returns:
True
on success
New in version 1.2.
- Parameters:
partNum (int) –
- deleteRing(self, ringNum: int, partNum: int = 0) bool ¶
Deletes a ring in polygon or multipolygon. Ring 0 is outer ring and can’t be deleted.
- Return type:
bool
- Returns:
True
on success
New in version 1.2.
- Parameters:
ringNum (int) –
partNum (int = 0) –
- deleteVertex(self, atVertex: int) bool ¶
Deletes the vertex at the given position number and item (first number is index 0)
- Return type:
bool
- 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?)- Parameters:
atVertex (int) –
- densifyByCount(self, extraNodesPerSegment: int) 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. 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
New in version 3.0.
- Parameters:
extraNodesPerSegment (int) –
- Return type:
- densifyByDistance(self, distance: float) 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
. 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
New in version 3.0.
- Parameters:
distance (float) –
- Return type:
- difference(self, geometry: QgsGeometry, parameters: QgsGeometryParameters = QgsGeometryParameters()) QgsGeometry ¶
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.- Parameters:
geometry (QgsGeometry) –
parameters (
QgsGeometryParameters
= QgsGeometryParameters()) –
- Return type:
- disjoint(self, geometry: QgsGeometry) bool ¶
Returns
True
if the geometry is disjoint of anothergeometry
.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 callingdisjoint()
directly. SeecreateGeometryEngine()
for details on how to use theQgsGeometryEngine
class.New in version 1.5.
- Parameters:
geometry (QgsGeometry) –
- Return type:
bool
- distance(self, geom: QgsGeometry) float ¶
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.- Parameters:
geom (QgsGeometry) –
- Return type:
float
- distanceToVertex(self, vertex: int) float ¶
Returns the distance along this geometry from its first vertex to the specified vertex.
- Parameters:
vertex (int) – vertex index to calculate distance to
- Return type:
float
- 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.New in version 2.16.
- draw(self, p: QPainter)¶
Draws the geometry onto a QPainter
- Parameters:
p (QPainter) – destination QPainter
New in version 2.10.
- equals(self, geometry: QgsGeometry) bool ¶
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
New in version 1.5.
- Parameters:
geometry (QgsGeometry) –
- Return type:
bool
- extendLine(self, startDistance: float, endDistance: float) QgsGeometry ¶
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.
New in version 3.0.
- Parameters:
startDistance (float) –
endDistance (float) –
- Return type:
- extrude(self, x: float, y: float) QgsGeometry ¶
Returns an extruded version of this geometry.
- Parameters:
x (float) –
y (float) –
- Return type:
- forcePolygonClockwise(self) QgsGeometry ¶
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
See also
See also
New in version 3.24.
- Return type:
- forcePolygonCounterClockwise(self) QgsGeometry ¶
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
See also
See also
New in version 3.24.
- Return type:
- forceRHR(self) 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. 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()
orforcePolygonCounterClockwise()
methods instead.See also
See also
See also
See also
New in version 3.6.
- Return type:
- frechetDistance(self, geom: QgsGeometry) float ¶
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.
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.6 or earlier.
See also
New in version 3.20.
- Parameters:
geom (QgsGeometry) –
- Return type:
float
- frechetDistanceDensify(self, geom: QgsGeometry, densifyFraction: float) float ¶
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. ThedensifyFraction
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 thedensifyFraction
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.
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.6 or earlier.
See also
New in version 3.20.
- Parameters:
geom (QgsGeometry) –
densifyFraction (float) –
- Return type:
float
- fromBox3D(box: QgsBox3D) QgsGeometry ¶
Creates a new geometry from a
QgsBox3D
objectNew in version 3.34.
- Parameters:
box (QgsBox3D) –
- Return type:
- fromMultiPointXY(multipoint: Iterable[QgsPointXY]) QgsGeometry ¶
Creates a new geometry from a
QgsMultiPointXY
object- Parameters:
multipoint (Iterable[QgsPointXY]) –
- Return type:
- fromMultiPolygonXY(multipoly: object) QgsGeometry ¶
Creates a new geometry from a
QgsMultiPolygonXY
.- Parameters:
multipoly (object) –
- Return type:
- fromMultiPolylineXY(multiline: object) QgsGeometry ¶
Creates a new geometry from a
QgsMultiPolylineXY
object.- Parameters:
multiline (object) –
- Return type:
- fromPoint(point: QgsPoint) QgsGeometry ¶
Creates a new geometry from a
QgsPoint
object.New in version 3.34.
- Parameters:
point (QgsPoint) –
- Return type:
- fromPointXY(point: QgsPointXY) QgsGeometry ¶
Creates a new geometry from a
QgsPointXY
object- Parameters:
point (QgsPointXY) –
- Return type:
- fromPolygonXY(polygon: object) QgsGeometry ¶
Creates a new polygon geometry from a list of lists of
QgsPointXY
.The first list of
QgsPointXY
objects specifies the exterior ring of the polygon, and the remaining lists specify any interior rings.Example¶
# Create a polygon geometry with a single exterior ring (a triangle) polygon = QgsGeometry.fromPolygonXY([[QgsPointXY(1, 2), QgsPointXY(5, 2), QgsPointXY(5, 10), QgsPointXY(1, 2)]])) # Create a donut shaped polygon geometry with an interior ring polygon = QgsGeometry.fromPolygonXY([[QgsPointXY(1, 2), QgsPointXY(5, 2), QgsPointXY(5, 10), QgsPointXY(1, 10), QgsPointXY(1, 2)], [QgsPointXY(3, 4), QgsPointXY(4, 4), QgsPointXY(4, 6), QgsPointXY(3, 6), QgsPointXY(3, 4)]])
- param polygon:
- type polygon:
object
- rtype:
QgsGeometry
- fromPolyline(polyline: Iterable[QgsPoint]) QgsGeometry ¶
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.
New in version 3.0.
- Parameters:
polyline (Iterable[QgsPoint]) –
- Return type:
- fromPolylineXY(polyline: Iterable[QgsPointXY]) QgsGeometry ¶
Creates a new LineString geometry from a list of
QgsPointXY
points.Using
fromPolyline()
is preferred, asfromPolyline()
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
New in version 3.0.
- Parameters:
polyline (Iterable[QgsPointXY]) –
- Return type:
- fromQPointF(point: QPointF | QPoint | float) QgsGeometry ¶
Construct geometry from a QPointF
- Parameters:
point (Union[QPointF) – source QPointF
New in version 2.7.
- Return type:
- fromQPolygonF(polygon: QPolygonF) QgsGeometry ¶
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:
polygon (QPolygonF) – source QPolygonF
New in version 2.7.
- Return type:
- fromRect(rect: QgsRectangle) QgsGeometry ¶
Creates a new geometry from a
QgsRectangle
- Parameters:
rect (QgsRectangle) –
- Return type:
- fromWkb(self, wkb: QByteArray | bytes | bytearray)¶
Set the geometry, feeding in the buffer containing OGC Well-Known Binary
New in version 3.0.
- Parameters:
wkb (Union[QByteArray) –
- fromWkt(wkt: str) QgsGeometry ¶
Creates a new geometry from a WKT string
- Parameters:
wkt (str) –
- Return type:
- get(self) QgsAbstractGeometry ¶
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
See also
New in version 3.0.
- Return type:
- hausdorffDistance(self, geom: QgsGeometry) float ¶
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
New in version 3.0.
- Parameters:
geom (QgsGeometry) –
- Return type:
float
- hausdorffDistanceDensify(self, geom: QgsGeometry, densifyFraction: float) float ¶
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. ThedensifyFraction
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 thedensifyFraction
parameter will make the distance returned approach the true Hausdorff distance for the geometries.In case of error -1 will be returned.
See also
New in version 3.0.
- Parameters:
geom (QgsGeometry) –
densifyFraction (float) –
- Return type:
float
- insertVertex(self, x: float, y: float, beforeVertex: int) 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. 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?)insertVertex(self, point:
QgsPoint
, beforeVertex: int) -> 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. ReturnsFalse
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?)- Parameters:
x (float) –
y (float) –
beforeVertex (int) –
- Return type:
bool
- interpolate(self, distance: float) QgsGeometry ¶
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
New in version 2.0.
- Parameters:
distance (float) –
- Return type:
- interpolateAngle(self, distance: float) float ¶
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:
distance (float) – distance along geometry
See also
New in version 3.0.
- Return type:
float
- intersection(self, geometry: QgsGeometry, parameters: QgsGeometryParameters = QgsGeometryParameters()) QgsGeometry ¶
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.- Parameters:
geometry (QgsGeometry) –
parameters (
QgsGeometryParameters
= QgsGeometryParameters()) –
- Return type:
- intersects(self, rectangle: QgsRectangle) bool ¶
Returns
True
if this geometry exactly intersects with arectangle
. 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
intersects(self, geometry:
QgsGeometry
) -> bool ReturnsTrue
if this geometry exactly intersects with anothergeometry
. 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 callingintersects()
directly. SeecreateGeometryEngine()
for details on how to use theQgsGeometryEngine
class.See also
- Parameters:
rectangle (QgsRectangle) –
- Return type:
bool
- isAxisParallelRectangle(self, maximumDeviation: float, simpleRectanglesOnly: bool = False) bool ¶
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 toTrue
then the method will only returnTrue
if the geometry is a simple rectangle consisting of 4 edges.New in version 3.20.
- Parameters:
maximumDeviation (float) –
simpleRectanglesOnly (bool = False) –
- Return type:
bool
- isEmpty(self) bool ¶
Returns
True
if the geometry is empty (eg a linestring with no vertices, or a collection with no geometries). A null geometry will always returnTrue
forisEmpty()
.See also
- Return type:
bool
- isGeosEqual(self, QgsGeometry) bool ¶
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
New in version 1.5.
- Return type:
bool
- isGeosValid(self, flags: Qgis.GeometryValidityFlags | Qgis.GeometryValidityFlag = Qgis.GeometryValidityFlags()) bool ¶
Checks validity of the geometry using GEOS.
The
flags
parameter indicates optional flags which control the type of validity checking performed.New in version 1.5.
- Parameters:
flags (Union[Qgis.GeometryValidityFlags) –
- Return type:
bool
- isMultipart(self) bool ¶
Returns
True
if WKB of the geometry is of WKBMulti* type- Return type:
bool
- isNull(self) bool ¶
Returns
True
if the geometry is null (ie, contains no underlying geometry accessible viaget()
orconstGet()
).See also
See also
See also
New in version 2.10.
- Return type:
bool
- isPolygonClockwise(self) bool ¶
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.
Warning
returns true if the geometry is not a polygon type or empty
See also
See also
See also
New in version 3.36.
- Return type:
bool
- isPolygonCounterClockwise(self) bool ¶
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.
Warning
returns false if the geometry is not a polygon type or empty
See also
See also
See also
New in version 3.36.
- Return type:
bool
- isSimple(self) bool ¶
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()
.New in version 3.0.
- Return type:
bool
- largestEmptyCircle(self, tolerance: float, boundary: QgsGeometry = QgsGeometry()) QgsGeometry ¶
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- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.8 or earlier.
New in version 3.20.
- Parameters:
tolerance (float) –
boundary (
QgsGeometry
= QgsGeometry()) –
- Return type:
- lastError(self) str ¶
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.
New in version 3.0.
- Return type:
str
- length(self) float ¶
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, theQgsDistanceArea
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
New in version 1.5.
- Return type:
float
- lineLocatePoint(self, point: QgsGeometry) float ¶
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:
point (QgsGeometry) – point to seek proximity to
- Return type:
float
- Returns:
distance along line, or -1 on error
Note
only valid for linestring geometries
See also
New in version 3.0.
- makeDifference(self, other: QgsGeometry) QgsGeometry ¶
Returns the geometry formed by modifying this geometry such that it does not intersect the other geometry.
- Parameters:
other (QgsGeometry) – geometry that should not be intersect
- Return type:
- Returns:
difference geometry, or empty geometry if difference could not be calculated
New in version 3.0.
- makeValid(self, method: Qgis.MakeValidMethod = Qgis.MakeValidMethod.Linework, keepCollapsed: bool = False) QgsGeometry ¶
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
andkeepCollapsed
arguments are available since QGIS 3.28. They require builds based on GEOS 3.10 or later.- Return type:
- Returns:
new valid
QgsGeometry
or null geometry on error- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.9 or earlier when the
method
is not Qgis.MakeValidMethod.Linework or thekeepCollapsed
option is set.
New in version 3.0.
- Parameters:
method (Qgis.MakeValidMethod = Qgis.MakeValidMethod.Linework) –
keepCollapsed (bool = False) –
- mapToPixel(self, mtp: QgsMapToPixel)¶
Transforms the geometry from map units to pixels in place.
- Parameters:
mtp (QgsMapToPixel) – map to pixel transform
New in version 2.10.
- mergeLines(self) QgsGeometry ¶
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line strings.
- Return type:
- 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.
New in version 3.0.
- minimalEnclosingCircle(self, segments: int = 36) Tuple[QgsGeometry, QgsPointXY, float] ¶
Returns the minimal enclosing circle for the geometry.
- Parameters:
segments (int = 36) – Number of segments used to segment geometry.
QgsEllipse.toPolygon()
- Return type:
Tuple[
QgsGeometry
,QgsPointXY
, float]- Returns:
the minimal enclosing circle as a QGIS geometry
center: Center of the minimal enclosing circle returneds
radius: Radius of the minimal enclosing circle returned
New in version 3.0.
- minimumClearance(self) float ¶
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.
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.5 or earlier.
New in version 3.20.
- Return type:
float
- minimumClearanceLine(self) QgsGeometry ¶
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.
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.5 or earlier.
New in version 3.20.
- Return type:
- minimumWidth(self) QgsGeometry ¶
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.
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.5 or earlier.
New in version 3.20.
- Return type:
- moveVertex(self, x: float, y: float, atVertex: int) bool ¶
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 geometrymoveVertex(self, p:
QgsPoint
, atVertex: int) -> bool Moves the vertex at the given position number and item (first number is index 0) to the given coordinates. ReturnsFalse
if atVertex does not correspond to a valid vertex on this geometry- Parameters:
x (float) –
y (float) –
atVertex (int) –
- Return type:
bool
- nearestPoint(self, other: QgsGeometry) QgsGeometry ¶
Returns the nearest (closest) point on this geometry to another geometry.
See also
New in version 2.14.
- Parameters:
other (QgsGeometry) –
- Return type:
- node(self) QgsGeometry ¶
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.
New in version 3.20.
- Return type:
- normalize(self)¶
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.
New in version 3.20.
- offsetCurve(self, distance: float, segments: int, joinStyle: Qgis.JoinStyle, miterLimit: float) QgsGeometry ¶
Returns an offset line at a given distance and side from an input line.
- Parameters:
distance (float) – buffer distance
segments (int) – for round joins, number of segments to approximate quarter-circle
joinStyle (Qgis.JoinStyle) – join style for corners in geometry
miterLimit (float) – limit on the miter ratio used for very sharp corners (JoinStyleMiter only)
New in version 2.4.
- Return type:
- orientedMinimumBoundingBox(self) Tuple[QgsGeometry, float, float, float, float] ¶
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
New in version 3.0.
- Return type:
Tuple[
QgsGeometry
, float, float, float, float]
- orthogonalize(self, tolerance: float = 1e-08, maxIterations: int = 1000, angleThreshold: float = 15) QgsGeometry ¶
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.
New in version 3.0.
- Parameters:
tolerance (float = 1e-08) –
maxIterations (int = 1000) –
angleThreshold (float = 15) –
- Return type:
- overlaps(self, geometry: QgsGeometry) bool ¶
Returns
True
if the geometry overlaps anothergeometry
.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 callingoverlaps()
directly. SeecreateGeometryEngine()
for details on how to use theQgsGeometryEngine
class.New in version 1.5.
- Parameters:
geometry (QgsGeometry) –
- Return type:
bool
- parts(self) QgsGeometryPartIterator ¶
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
See also
New in version 3.6.
- rtype:
QgsGeometryPartIterator
- pointOnSurface(self) QgsGeometry ¶
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
See also
- Return type:
- poleOfInaccessibility(self, precision: float) Tuple[QgsGeometry, float] ¶
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
See also
New in version 3.0.
- Parameters:
precision (float) –
- Return type:
Tuple[
QgsGeometry
, float]
- polygonOrientation(self) Qgis.AngularDirection ¶
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.
Warning
returns
Qgis
.AngularDirection.NoOrientation if the geometry is not a polygon type or emptyNew in version 3.36.
- Return type:
- polygonize(geometries: Iterable[QgsGeometry]) QgsGeometry ¶
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 callunaryUnion()
on the set of input geometries and then pass the result topolygonize()
. An empty geometry will be returned in the case of errors.New in version 3.0.
- Parameters:
geometries (Iterable[QgsGeometry]) –
- Return type:
- randomPointsInPolygon(self, count: int, seed: int = 0) QgsPolylineXY ¶
Returns a list of
count
random points generated inside a (multi)polygon geometry.Optionally, a specific random
seed
can be used when generating points. Ifseed
is 0, then a completely random sequence of points will be generated.This method works only with (multi)polygon geometry types.
- Raises:
TypeError – if the geometry is not a polygon type
ValueError – if the geometry is null
New in version 3.10.
- Parameters:
count (int) –
seed (int = 0) –
- Return type:
QgsPolylineXY
- removeDuplicateNodes(self, epsilon: float = 4 * DBL_EPSILON, useZValues: bool = False) bool ¶
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
isTrue
, 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, orFalse
if no duplicate nodes were found.New in version 3.0.
- Parameters:
epsilon (float = 4*DBL_EPSILON) –
useZValues (bool = False) –
- Return type:
bool
- removeInteriorRings(self, minimumAllowedArea: float = -1) QgsGeometry ¶
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.
New in version 3.0.
- Parameters:
minimumAllowedArea (float = -1) –
- Return type:
- requiresConversionToStraightSegments(self) bool ¶
Returns
True
if the geometry is a curved geometry type which requires conversion to display as straight line segments.See also
New in version 2.10.
- Return type:
bool
- reshapeGeometry(self, reshapeLineString: QgsLineString) Qgis.GeometryOperationResult ¶
Replaces a part of this geometry with another line
- Return type:
- Returns:
OperationResult a result code: success or reason of failure
- Parameters:
reshapeLineString (QgsLineString) –
- rotate(self, rotation: float, center: QgsPointXY) Qgis.GeometryOperationResult ¶
Rotate this geometry around the Z axis
- Parameters:
rotation (float) – clockwise rotation in degrees
center (QgsPointXY) – rotation center
- Return type:
- Returns:
OperationResult a result code: success or reason of failure
- roundWaves(self, wavelength: float, amplitude: float, strictWavelength: bool = False) QgsGeometry ¶
Constructs rounded (sine-like) waves along the boundary of the geometry, with the specified
wavelength
andamplitude
.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. IfstrictWavelength
is set toTrue
then thewavelength
will be used exactly and an incomplete pattern may be used for the final waveform.See also
New in version 3.24.
- Parameters:
wavelength (float) –
amplitude (float) –
strictWavelength (bool = False) –
- Return type:
- roundWavesRandomized(self, minimumWavelength: float, maximumWavelength: float, minimumAmplitude: float, maximumAmplitude: float, seed: int = 0) QgsGeometry ¶
Constructs randomized rounded (sine-like) waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
The
minimumWavelength
andmaximumWavelength
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
andmaximumAmplitude
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. Ifseed
is 0, then a completely random sequence of points will be generated.See also
New in version 3.24.
- Parameters:
minimumWavelength (float) –
maximumWavelength (float) –
minimumAmplitude (float) –
maximumAmplitude (float) –
seed (int = 0) –
- Return type:
- set(self, geometry: QgsAbstractGeometry)¶
Sets the underlying geometry store. Ownership of geometry is transferred.
Note
In QGIS 2.x this method was named
setGeometry()
.Note
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
See also
New in version 3.0.
- Parameters:
geometry (QgsAbstractGeometry) –
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.
New in version 3.20.
- Parameters:
other (QgsGeometry) –
- Return type:
- shortestLine(self, other: QgsGeometry) QgsGeometry ¶
Returns the shortest line joining this geometry to another geometry.
See also
Warning
QgsGeometry
objects are inherently Cartesian/planar geometries, and the line returned by this method is calculated using strictly Cartesian mathematics. SeeQgsDistanceArea
for similar methods which account for the curvature of an ellipsoidal body such as the Earth.New in version 2.14.
- Parameters:
other (QgsGeometry) –
- Return type:
- simplify(self, tolerance: float) QgsGeometry ¶
Returns a simplified version of this geometry using a specified tolerance value
- Parameters:
tolerance (float) –
- Return type:
- simplifyCoverageVW(self, tolerance: float, preserveBoundary: bool) QgsGeometry ¶
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:
tolerance (float) – A tolerance parameter in linear units.
preserveBoundary (bool) – Set to
True
to preserve the outside edges of the coverage without simplification, orFalse
to allow them to be simplified.
This method requires a QGIS build based on GEOS 3.12 or later.
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.11 or earlier.
See also
New in version 3.36.
- Return type:
- singleSidedBuffer(self, distance: float, segments: int, side: Qgis.BufferSide, joinStyle: Qgis.JoinStyle = Qgis.JoinStyle.Round, miterLimit: float = 2) QgsGeometry ¶
Returns a single sided buffer for a (multi)line geometry. The buffer is only applied to one side of the line.
- Parameters:
distance (float) – buffer distance
segments (int) – for round joins, number of segments to approximate quarter-circle
side (Qgis.BufferSide) – side of geometry to buffer
joinStyle (Qgis.JoinStyle = Qgis.JoinStyle.Round) – join style for corners
miterLimit (float = 2) – limit on the miter ratio used for very sharp corners
- Return type:
- Returns:
buffered geometry, or an empty geometry if buffer could not be calculated
See also
See also
New in version 3.0.
- smooth(self, iterations: int = 1, offset: float = 0.25, minimumDistance: float = -1, maxAngle: float = 180) QgsGeometry ¶
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:
iterations (int = 1) – number of smoothing iterations to run. More iterations results in a smoother geometry
offset (float = 0.25) – 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 (float = -1) – minimum segment length to apply smoothing to
maxAngle (float = 180) – maximum angle at node (0-180) at which smoothing will be applied
New in version 2.9.
- Return type:
- snappedToGrid(self, hSpacing: float, vSpacing: float, dSpacing: float = 0, mSpacing: float = 0) QgsGeometry ¶
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:
hSpacing (float) – Horizontal spacing of the grid (x axis). 0 to disable.
vSpacing (float) – Vertical spacing of the grid (y axis). 0 to disable.
dSpacing (float = 0) – Depth spacing of the grid (z axis). 0 (default) to disable.
mSpacing (float = 0) – Custom dimension spacing of the grid (m axis). 0 (default) to disable.
New in version 3.0.
- Return type:
- splitGeometry(self, splitLine: List[QgsPoint | QgsPointXY], topological: bool, splitFeature: bool = True) Tuple[Qgis.GeometryOperationResult, List[QgsPoint] | List[QgsPointXY], List[QgsPoint] | List[QgsPointXY]] ¶
Splits this geometry according to a given line.
- Parameters:
splitLine (List[Union[QgsPoint) – the line that splits the geometry
topological (bool) –
True
if topological editing is enabledsplitFeature (bool = True) – Set to
True
if you want to split a feature, otherwise set toFalse
to split parts
- Returns:
a tuple (
Qgis
.GeometryOperationResult, List[QgsGeometry
], List[Union[QgsPoint
,QgsPointXY
]]) (result code, list of new geometries, list of topological points)
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)
splitGeometry(self, curve:
QgsCurve
, preserveCircular: bool, topological: bool, splitFeature: bool = True) -> Tuple[Qgis.GeometryOperationResult, List[QgsGeometry], List[QgsPoint]] Splits this geometry according to a given curve.- Parameters:
curve – the curve that splits the geometry
param[out] newGeometries list 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. :param preserveCircular: whether if circular strings are preserved after splitting :param topological:True
if topological editing is enabled param[out] topologyTestPoints points that need to be tested for topological completeness in the dataset :param splitFeature: Set toTrue
if you want to split a feature, otherwise set toFalse
to split parts- Return type:
Tuple[Qgis.GeometryOperationResult, Union[List[QgsPoint], List[QgsPointXY]], Union[List[QgsPoint], List[QgsPointXY]]]
- Returns:
OperationResult a result code: success or reason of failure
New in version 3.16.
- sqrDistToVertexAt(self, point: QgsPointXY, atVertex: int) float ¶
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))
- Parameters:
point (QgsPointXY) –
atVertex (int) –
- Return type:
float
- squareWaves(self, wavelength: float, amplitude: float, strictWavelength: bool = False) QgsGeometry ¶
Constructs square waves along the boundary of the geometry, with the specified
wavelength
andamplitude
.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. IfstrictWavelength
is set toTrue
then thewavelength
will be used exactly and an incomplete pattern may be used for the final waveform.See also
New in version 3.24.
- Parameters:
wavelength (float) –
amplitude (float) –
strictWavelength (bool = False) –
- Return type:
- squareWavesRandomized(self, minimumWavelength: float, maximumWavelength: float, minimumAmplitude: float, maximumAmplitude: float, seed: int = 0) QgsGeometry ¶
Constructs randomized square waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
The
minimumWavelength
andmaximumWavelength
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
andmaximumAmplitude
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. Ifseed
is 0, then a completely random sequence of points will be generated.See also
New in version 3.24.
- Parameters:
minimumWavelength (float) –
maximumWavelength (float) –
minimumAmplitude (float) –
maximumAmplitude (float) –
seed (int = 0) –
- Return type:
- staticMetaObject = <PyQt5.QtCore.QMetaObject object>¶
- subdivide(self, maxNodes: int = 256, parameters: QgsGeometryParameters = QgsGeometryParameters()) QgsGeometry ¶
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.New in version 3.0.
- Parameters:
maxNodes (int = 256) –
parameters (
QgsGeometryParameters
= QgsGeometryParameters()) –
- Return type:
- symDifference(self, geometry: QgsGeometry, parameters: QgsGeometryParameters = QgsGeometryParameters()) QgsGeometry ¶
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.- Parameters:
geometry (QgsGeometry) –
parameters (
QgsGeometryParameters
= QgsGeometryParameters()) –
- Return type:
- taperedBuffer(self, startWidth: float, endWidth: float, segments: int) QgsGeometry ¶
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 ofendWidth
. Note that unlikebuffer()
methods,startWidth
andendWidth
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
See also
See also
New in version 3.2.
- Parameters:
startWidth (float) –
endWidth (float) –
segments (int) –
- Return type:
- toggleCircularAtVertex(self, atVertex: int) bool ¶
Converts the vertex at the given position from/to circular
- Return type:
bool
- 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).
New in version 3.20.
- Parameters:
atVertex (int) –
- touches(self, geometry: QgsGeometry) bool ¶
Returns
True
if the geometry touches anothergeometry
.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 callingtouches()
directly. SeecreateGeometryEngine()
for details on how to use theQgsGeometryEngine
class.New in version 1.5.
- Parameters:
geometry (QgsGeometry) –
- Return type:
bool
- transform(self, ct: QgsCoordinateTransform, direction: Qgis.TransformDirection = Qgis.TransformDirection.Forward, transformZ: bool = False) Qgis.GeometryOperationResult ¶
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
toTrue
. 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
transform(self, t: QTransform, zTranslate: float = 0, zScale: float = 1, mTranslate: float = 0, mScale: float = 1) -> Qgis.GeometryOperationResult 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 viazTranslate
. Similarly, m-values can be scaled viamScale
and translated viamTranslate
.- Return type:
- Returns:
OperationResult a result code: success or reason of failure
- Parameters:
ct (QgsCoordinateTransform) –
direction (Qgis.TransformDirection = Qgis.TransformDirection.Forward) –
transformZ (bool = False) –
- translate(self, dx: float, dy: float, dz: float = 0, dm: float = 0) Qgis.GeometryOperationResult ¶
Translates this geometry by dx, dy, dz and dm.
- Return type:
- Returns:
OperationResult a result code: success or reason of failure
- Parameters:
dx (float) –
dy (float) –
dz (float = 0) –
dm (float = 0) –
- triangularWaves(self, wavelength: float, amplitude: float, strictWavelength: bool = False) QgsGeometry ¶
Constructs triangular waves along the boundary of the geometry, with the specified
wavelength
andamplitude
.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. IfstrictWavelength
is set toTrue
then thewavelength
will be used exactly and an incomplete pattern may be used for the final waveform.See also
New in version 3.24.
- Parameters:
wavelength (float) –
amplitude (float) –
strictWavelength (bool = False) –
- Return type:
- triangularWavesRandomized(self, minimumWavelength: float, maximumWavelength: float, minimumAmplitude: float, maximumAmplitude: float, seed: int = 0) QgsGeometry ¶
Constructs randomized triangular waves along the boundary of the geometry, with the specified wavelength and amplitude ranges.
The
minimumWavelength
andmaximumWavelength
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
andmaximumAmplitude
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. Ifseed
is 0, then a completely random sequence of points will be generated.See also
New in version 3.24.
- Parameters:
minimumWavelength (float) –
maximumWavelength (float) –
minimumAmplitude (float) –
maximumAmplitude (float) –
seed (int = 0) –
- Return type:
- type(self) Qgis.GeometryType ¶
Returns type of the geometry as a
Qgis
.GeometryTypeSee also
- Return type:
- unaryUnion(geometries: Iterable[QgsGeometry], parameters: QgsGeometryParameters = QgsGeometryParameters()) QgsGeometry ¶
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.- Parameters:
geometries (Iterable[QgsGeometry]) –
parameters (
QgsGeometryParameters
= QgsGeometryParameters()) –
- Return type:
- unionCoverage(self) QgsGeometry ¶
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
New in version 3.36.
- Return type:
- validateCoverage(self, gapWidth: float) Tuple[Qgis.CoverageValidityResult, QgsGeometry] ¶
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:
gapWidth (float) – The maximum width of gaps to detect.
- Return type:
- Returns:
validity check result
invalidEdges: When 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.
This method requires a QGIS build based on GEOS 3.12 or later.
- Raises:
QgsNotSupportedException – on QGIS builds based on GEOS 3.11 or earlier.
See also
New in version 3.36.
- validateGeometry(self, method: Qgis.GeometryValidationEngine = Qgis.GeometryValidationEngine.QgisInternal, flags: Qgis.GeometryValidityFlags | Qgis.GeometryValidityFlag = Qgis.GeometryValidityFlags()) List[QgsGeometry.Error] ¶
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.New in version 1.5.
- Parameters:
method (Qgis.GeometryValidationEngine = Qgis.GeometryValidationEngine.QgisInternal) –
flags (Union[Qgis.GeometryValidityFlags) –
- Return type:
List[QgsGeometry.Error]
- variableWidthBufferByM(self, segments: int) QgsGeometry ¶
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
See also
See also
New in version 3.2.
- Parameters:
segments (int) –
- Return type:
- vertexIdFromVertexNr(self, number: int) Tuple[bool, QgsVertexId] ¶
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
New in version 2.10.
- Parameters:
number (int) –
- Return type:
Tuple[bool, QgsVertexId]
- vertexNrFromVertexId(self, id: QgsVertexId) int ¶
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
New in version 2.10.
- Parameters:
id (QgsVertexId) –
- Return type:
int
- vertices(self) QgsVertexIterator ¶
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
New in version 3.0.
- rtype:
QgsVertexIterator
- voronoiDiagram(self, extent: QgsGeometry = QgsGeometry(), tolerance: float = 0, edgesOnly: bool = False) QgsGeometry ¶
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. Thetolerance
parameter specifies an optional snapping tolerance which can be used to improve the robustness of the diagram calculation. IfedgesOnly
isTrue
than line string boundary geometries will be returned instead of polygons. An empty geometry will be returned if the diagram could not be calculated.New in version 3.0.
- Parameters:
extent (
QgsGeometry
= QgsGeometry()) –tolerance (float = 0) –
edgesOnly (bool = False) –
- Return type:
- within(self, geometry: QgsGeometry) bool ¶
Returns
True
if the geometry is completely within anothergeometry
.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 callingwithin()
directly. SeecreateGeometryEngine()
for details on how to use theQgsGeometryEngine
class.New in version 1.5.
- Parameters:
geometry (QgsGeometry) –
- Return type:
bool
- wkbSize(self, flags: QgsAbstractGeometry.WkbFlags | QgsAbstractGeometry.WkbFlag = QgsAbstractGeometry.WkbFlags()) int ¶
Returns the length of the QByteArray returned by
asWkb()
The optional
flags
argument specifies flags controlling WKB export behaviorNew in version 3.16.
- Parameters:
flags (Union[QgsAbstractGeometry.WkbFlags) –
- Return type:
int
- wkbType(self) Qgis.WkbType ¶
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
See also
- Return type: