Class: QgsGeometry¶
-
class
qgis.core.
QgsGeometry
¶ Bases:
sip.wrapper
Constructor
QgsGeometry(QgsGeometry) Copy constructor will prompt a deep copy of the object
QgsGeometry(geom: QgsAbstractGeometry) Creates a geometry from an abstract geometry object. Ownership of geom is transferred.
New in version 2.10.
A geometry is the spatial representation of a feature. Since QGIS 2.10, QgsGeometry acts as a generic container for geometry objects. QgsGeometry is implicitly shared, so making copies of geometries is inexpensive. The geometry container class can also be stored inside a QVariant object.
The actual geometry representation is stored as a QgsAbstractGeometry within the container, and can be accessed via the get() method or set using the set() method.
Enums
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.
Returns the area of the geometry using GEOS
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
Returns the bounding box of the geometry.
Returns true if the bounding box of this geometry intersects with a
rectangle
.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.
Creates a new multipart geometry from a list of QgsGeometry objects
Returns 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 non-modifiable (const) reference to the underlying abstract geometry primitive.
Returns Java-style iterator for traversal of parts of the geometry.
Tests for containment of a point (uses GEOS)
Converts geometry collection to a the desired geometry type subclass (multi-point, multi-linestring or multi-polygon).
Upgrades a point list from QgsPointXY to
QgsPoint
Converts single type geometry into multitype geometry e.g.
Converts multi type geometry into single type geometry e.g.
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
Creates a QgsPolygonXYfrom a QPolygonF.
Creates a QgsPolylineXY from a QPolygonF.
Creates a wedge shaped buffer from a
center
point.Test for if geometry crosses another (uses GEOS)
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.
Tests for if geometry is disjoint of another (uses GEOS)
Returns the minimum distance between this geometry and another geometry, using GEOS.
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 Right-Hand-Rule, in which the area that is bounded by a polygon is to the right of the boundary.
Creates a new geometry from a QgsMultiPointXY object
Creates a new geometry from a
QgsMultiPolygon
Creates a new geometry from a QgsMultiPolylineXY object
Creates a new geometry from a QgsPointXY object
Creates a new geometry from a
QgsPolygon
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 a
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* type
Returns true if the geometry is null (ie, contains no underlying geometry accessible via geometry() ).
Determines whether the geometry is simple (according to OGC definition), i.e.
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 length of geometry using GEOS
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.
Moves the vertex at the given position number and item (first number is index 0) to the given coordinates.
Returns the nearest point on this geometry to another geometry.
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.
Test for if geometry overlaps another (uses GEOS)
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.
Creates a GeometryCollection geometry containing possible polygons formed from the constituent linework of a set of
geometries
.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
Sets the underlying geometry store.
Returns the shortest line joining this geometry to another geometry.
Returns a simplified version of this geometry using a specified tolerance value
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))
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.
Test for if geometry touch another (uses GEOS)
Transforms this geometry as described by the coordinate transform
ct
.Translates this geometry by dx, dy, dz and dm.
Returns type of the geometry as a QgsWkbTypes.GeometryType
Compute the unary union on a list of
geometries
.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.
Test for if geometry is within another (uses GEOS)
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
Signals
Attributes
-
AddPartNotMultiGeometry
= 1008¶
-
AddPartSelectedGeometryNotFound
= 1007¶
-
AddRingCrossesExistingRings
= 1011¶
-
AddRingNotClosed
= 1009¶
-
AddRingNotInExistingFeature
= 1012¶
-
AddRingNotValid
= 1010¶
-
class
BufferSide
¶ Bases:
int
-
baseClass
¶ alias of
QgsGeometry
-
-
CapFlat
= 2¶
-
CapRound
= 1¶
-
CapSquare
= 3¶
-
class
EndCapStyle
¶ Bases:
int
-
baseClass
¶ alias of
QgsGeometry
-
-
class
Error
¶ Bases:
sip.wrapper
QgsGeometry.Error(m: str) QgsGeometry.Error(m: str, p: QgsPointXY) QgsGeometry.Error(QgsGeometry.Error)
-
what
(self) → str¶ A human readable error message containing details about the error.
-
where
(self) → QgsPointXY¶ The coordinates at which the error is located and should be visualized.
-
-
FlagAllowSelfTouchingHoles
= 1¶
-
GeometryEngineError
= 1005¶
-
InvalidBaseGeometry
= 1001¶
-
InvalidInputGeometryType
= 1002¶
-
class
JoinStyle
¶ Bases:
int
-
baseClass
¶ alias of
QgsGeometry
-
-
JoinStyleBevel
= 3¶
-
JoinStyleMiter
= 2¶
-
JoinStyleRound
= 1¶
-
LayerNotEditable
= 1006¶
-
NothingHappened
= 1000¶
-
class
OperationResult
¶ Bases:
int
-
SelectionIsEmpty
= 1003¶
-
SelectionIsGreaterThanOne
= 1004¶
-
SideLeft
= 0¶
-
SideRight
= 1¶
-
SplitCannotSplitPoint
= 1013¶
-
Success
= 0¶
-
class
ValidationMethod
¶ Bases:
int
-
ValidatorGeos
= 1¶
-
ValidatorQgisInternal
= 0¶
-
class
ValidityFlag
¶ Bases:
int
-
class
ValidityFlags
¶ Bases:
sip.wrapper
QgsGeometry.ValidityFlags(Union[QgsGeometry.ValidityFlags, QgsGeometry.ValidityFlag]) QgsGeometry.ValidityFlags(QgsGeometry.ValidityFlags)
-
addPart
(self, part: QgsAbstractGeometry, geomType: QgsWkbTypes.GeometryType = QgsWkbTypes.UnknownGeometry) → QgsGeometry.OperationResult¶ Adds a new part to this geometry.
- Parameters
part – part to add (ownership is transferred)
geomType – default geometry type to create if no existing geometry
- Returns
OperationResult a result code: success or reason of failure
-
addPartGeometry
(self, newPart: QgsGeometry) → QgsGeometry.OperationResult¶ Adds a new island polygon to a multipolygon feature
- Returns
OperationResult a result code: success or reason of failure
Note
available in python bindings as addPartGeometry
-
addPoints
(self, points: object, geomType: QgsWkbTypes.GeometryType = QgsWkbTypes.UnknownGeometry) → QgsGeometry.OperationResult¶ Adds a new part to a the geometry.
- Parameters
points – points describing part to add
geomType – default geometry type to create if no existing geometry
- Returns
OperationResult a result code: success or reason of failure
-
addPointsXY
(self, points: Iterable[QgsPointXY], geomType: QgsWkbTypes.GeometryType = QgsWkbTypes.UnknownGeometry) → QgsGeometry.OperationResult¶ Adds a new part to a the geometry.
- Parameters
points – points describing part to add
geomType – default geometry type to create if no existing geometry
- Returns
OperationResult a result code: success or reason of failure
-
addRing
(self, ring: Iterable[QgsPointXY]) → QgsGeometry.OperationResult¶ Adds a new ring to this geometry. This makes only sense for polygon and multipolygons.
- Parameters
ring – The ring to be added
- Returns
OperationResult a result code: success or reason of failure
addRing(self, ring: QgsCurve) -> QgsGeometry.OperationResult Adds a new ring to this geometry. This makes only sense for polygon and multipolygons.
- Parameters
ring – The ring to be added
- 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:
1. If the given vertex index is at the end of a linestring, the adjacent index will be -1 (for “no adjacent vertex”) 2. If the given vertex index is at the end of a linear ring (such as in a polygon), the adjacent index will take into account the first vertex is equal to the last vertex (and will skip equal vertex positions).
-
angleAtVertex
(self, vertex: int) → float¶ Returns the bisector angle for this geometry at the specified vertex.
- Parameters
vertex – vertex index to calculate bisector angle at
- Returns
bisector angle, in radians clockwise from north
See also
New in version 3.0.
-
area
(self) → float¶ Returns the area of the geometry using GEOS
New in version 1.5.
-
asGeometryCollection
(self) → List[QgsGeometry]¶ Returns contents of the geometry as a list of geometries
New in version 1.1.
-
asJson
(self, precision: int = 17) → str¶ Exports the geometry to a GeoJSON string.
-
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. If the geometry is not a multi-point type, a TypeError will be raised. If the geometry is null, a ValueError will be raised.
-
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. If the geometry is not a multi-polygon type, a TypeError will be raised. If the geometry is null, a ValueError will be raised.
-
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. If the geometry is not a multi-linestring type, a TypeError will be raised. If the geometry is null, a ValueError will be raised.
-
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. If the geometry is not a single-point type, a TypeError will be raised. If the geometry is null, a ValueError will be raised.
-
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. If the geometry is not a single-polygon type, a TypeError will be raised. If the geometry is null, a ValueError will be raised.
-
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) geometry types. If the geometry is not a single-line type, a TypeError will be raised. If the geometry is null, a ValueError will be raised.
-
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.
-
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.
New in version 2.7.
-
asWkb
(self) → QByteArray¶ Export the geometry to WKB
New in version 3.0.
-
asWkt
(self, precision: int = 17) → str¶ Exports the geometry to WKT
- Returns
true in case of success and false else
Note
precision parameter added in QGIS 2.4
-
avoidIntersections
(self, avoidIntersectionsLayers: Iterable[QgsVectorLayer]) → int¶ Modifies geometry to avoid intersections with the layers specified in project properties
- Parameters
avoidIntersectionsLayers – list of layers to check for intersections
- Returns
0 in case of success, 1 if geometry is not of polygon type, 2 if avoid intersection would change the geometry type, 3 other error during intersection removal
New in version 1.5.
-
boundingBox
(self) → QgsRectangle¶ Returns the bounding box of the geometry.
See also
-
boundingBoxIntersects
(self, rectangle: QgsRectangle) → bool¶ Returns true if the bounding box of this geometry intersects with a
rectangle
. Since this test only considers the bounding box of the geometry, is is very fast to calculate and handles invalid geometries.See also
New in version 3.0.
boundingBoxIntersects(self, geometry: QgsGeometry) -> bool Returns true if the bounding box of this geometry intersects with the bounding box of another
geometry
. Since this test only considers the bounding box of the geometries, is is very fast to calculate and handles invalid geometries.See also
New in version 3.0.
-
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: QgsGeometry.EndCapStyle, joinStyle: QgsGeometry.JoinStyle, miterLimit: float) -> QgsGeometry Returns a buffer region around the geometry, with additional style options.
- Parameters
distance – buffer distance
segments – for round joins, number of segments to approximate quarter-circle
endCapStyle – end cap style
joinStyle – join style for corners in geometry
miterLimit – limit on the miter ratio used for very sharp corners (JoinStyleMiter only)
See also
See also
New in version 2.4.
-
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 error() 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
-
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.
-
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 – Specifies the point for search
afterVertex – Receives index of the vertex after the closest segment. The vertex before the closest segment is always afterVertex - 1
leftOf – Out: Returns if the point lies on the left of left side of the geometry ( < 0 means left, > 0 means right, 0 indicates that the test was unsuccessful, e.g. for a point exactly on the line)
epsilon – epsilon for segment snapping
- Returns
The squared Cartesian distance is also returned in sqrDist, negative number on error
minDistPoint: Receives the nearest point on the segment
-
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 – point to search for
beforeVertex – will be set to the vertex index of the previous vertex from the closest one. Will be set to -1 if not present.
afterVertex – will be set to the vertex index of the next vertex after the closest one. Will be set to -1 if not present.
sqrDist – will be set to the square distance between the closest vertex and the specified point
- Returns
closest point in geometry. If not found (empty geometry), returns null point nad sqrDist is negative.
atVertex: will be set to the vertex index of the closest found vertex
-
closestVertexWithContext
(self, point: QgsPointXY) → Tuple[float, int]¶ Searches for the closest vertex in this geometry to the given point.
- Parameters
point – Specifiest the point for search
- Returns
The squared Cartesian distance is also returned in sqrDist, negative number on error
atVertex: Receives index of the closest vertex
-
collectGeometry
(geometries: Iterable[QgsGeometry]) → QgsGeometry¶ Creates a new multipart geometry from a list of QgsGeometry objects
-
combine
(self, geometry: QgsGeometry) → 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 error() on the returned geometry.
Note
this operation is not called union since its a reserved word in C++.
-
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
, QgsPolygonXYorQgsMultiPolygon
. The 2 types should match.- Parameters
p1 – first geometry object
p2 – second geometry object
epsilon – maximum difference for coordinates between the objects
- Returns
true if objects are - polylines 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.
-
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.
-
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.parts(): print(part.asWkt()) # single part geometries only have one part - this loop will iterate once only geometry = QgsGeometry.fromWkt( 'LineString( 0 0, 10 10 )' ) for part in geometry.parts(): print(part.asWkt()) # part iteration can also be combined with vertex iteration geometry = QgsGeometry.fromWkt( 'MultiPolygon((( 0 0, 0 10, 10 10, 10 0, 0 0 ),( 5 5, 5 6, 6 6, 6 5, 5 5)),((20 2, 22 2, 22 4, 20 4, 20 2)))' ) for part in geometry.parts(): for v in part.vertices(): print(v.x(), v.y())
See also
See also
New in version 3.6.
-
contains
(self, p: QgsPointXY) → bool¶ Tests for containment of a point (uses GEOS)
contains(self, geometry: QgsGeometry) -> bool Tests for if geometry is contained in another (uses GEOS)
New in version 1.5.
-
convertGeometryCollectionToSubclass
(self, geomType: QgsWkbTypes.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.
- Returns
true in case of success and false else
New in version 3.2.
-
convertPointList
(input: Iterable[QgsPointXY], output: object)¶ Upgrades a point list from QgsPointXY to
QgsPoint
- Parameters
input – list of QgsPointXY objects to be upgraded
output – destination for list of points converted to
QgsPoint
convertPointList(input: object, output: Iterable[QgsPointXY]) Downgrades a point list from QgsPoint to
QgsPointXY
- Parameters
input – list of QgsPoint objects to be downgraded
output – destination for list of points converted to
QgsPointXY
-
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.
- Returns
true in case of success and false 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.
- Returns
true in case of success and false 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 – segmentation tolerance
toleranceType – maximum segmentation angle or maximum difference between approximation and curve
New in version 2.10.
-
convertToType
(self, destType: QgsWkbTypes.GeometryType, destMultipart: bool = False) → QgsGeometry¶ Try to convert the geometry to the requested type
- Parameters
destType – the geometry type to be converted to
destMultipart – determines if the output geometry will be multipart or not
- Returns
the converted geometry or None if the conversion fails.
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 error() on the returned geometry.
-
createGeometryEngine
(geometry: QgsAbstractGeometry) → QgsGeometryEngine¶ Creates and returns a new geometry engine
-
createPolygonFromQPolygonF
(polygon: QPolygonF) → object¶ Creates a QgsPolygonXYfrom a QPolygonF.
- Parameters
polygon – source polygon
- Returns
See also
-
createPolylineFromQPolygonF
(polygon: QPolygonF) → List[QgsPointXY]¶ Creates a QgsPolylineXY from a QPolygonF.
- Parameters
polygon – source polygon
- Returns
QgsPolylineXY
See also
-
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.
-
crosses
(self, geometry: QgsGeometry) → bool¶ Test for if geometry crosses another (uses GEOS)
New in version 1.5.
-
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
is true than line string boundary geometries will be returned instead of polygons. An empty geometry will be returned if the diagram could not be calculated.New in version 3.0.
-
deletePart
(self, partNum: int) → bool¶ Deletes part identified by the part number
- Returns
true on success
New in version 1.2.
-
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.
- Returns
true on success
New in version 1.2.
-
deleteVertex
(self, atVertex: int) → bool¶ Deletes the vertex at the given position number and item (first number is index 0)
- Returns
false if atVertex does not correspond to a valid vertex on this geometry (including if this geometry is a Point), or if the number of remaining vertices in the linestring would be less than two. It is up to the caller to distinguish between these error conditions. (Or maybe we add another method to this object to help make the distinction?)
-
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.
-
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.
-
difference
(self, geometry: QgsGeometry) → 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 error() on the returned geometry.
-
disjoint
(self, geometry: QgsGeometry) → bool¶ Tests for if geometry is disjoint of another (uses GEOS)
New in version 1.5.
-
distance
(self, geom: QgsGeometry) → float¶ Returns the minimum distance between this geometry and another geometry, using GEOS. Will return a negative value if a geometry is missing.
- Parameters
geom – geometry to find minimum distance to
-
distanceToVertex
(self, vertex: int) → float¶ Returns the distance along this geometry from its first vertex to the specified vertex.
- Parameters
vertex – vertex index to calculate distance to
- Returns
distance to vertex (following geometry), or -1 for invalid vertex numbers
New in version 2.16.
-
draw
(self, p: QPainter)¶ Draws the geometry onto a QPainter
- Parameters
p – 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.
-
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.
-
extrude
(self, x: float, y: float) → QgsGeometry¶ Returns an extruded version of this geometry.
-
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.
New in version 3.6.
-
fromMultiPointXY
(multipoint: object) → QgsGeometry¶ Creates a new geometry from a QgsMultiPointXY object
-
fromMultiPolygonXY
(multipoly: object) → QgsGeometry¶ Creates a new geometry from a
QgsMultiPolygon
-
fromMultiPolylineXY
(multiline: object) → QgsGeometry¶ Creates a new geometry from a QgsMultiPolylineXY object
-
fromPointXY
(point: QgsPointXY) → QgsGeometry¶ Creates a new geometry from a QgsPointXY object
-
fromPolygonXY
(polygon: object) → QgsGeometry¶ Creates a new geometry from a
QgsPolygon
-
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.
-
fromPolylineXY
(polyline: Iterable[QgsPointXY]) → QgsGeometry¶ Creates a new LineString geometry from a list of QgsPointXY points.
Using fromPolyline() is preferred, as fromPolyline() is more efficient and will respect any Z or M dimensions present in the input points.
Note
In QGIS 2.x this method was available as fromPolyline().
See also
New in version 3.0.
-
fromQPointF
(point: Union[QPointF, QPoint]) → QgsGeometry¶ Construct geometry from a QPointF
- Parameters
point – source QPointF
New in version 2.7.
-
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 – source QPolygonF
New in version 2.7.
-
fromRect
(rect: QgsRectangle) → QgsGeometry¶ Creates a new geometry from a
QgsRectangle
-
fromWkb
(self, wkb: Union[QByteArray, bytes, bytearray])¶ Set the geometry, feeding in the buffer containing OGC Well-Known Binary
New in version 3.0.
-
fromWkt
(wkt: str) → QgsGeometry¶ Creates a new geometry from a WKT string
-
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.
-
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.
-
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 the
densifyFraction
parameter will make the distance returned approach the true Hausdorff distance for the geometries.In case of error -1 will be returned.
See also
New in version 3.0.
-
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. 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?)
-
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.
-
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 – distance along geometry
See also
New in version 3.0.
-
intersection
(self, geometry: QgsGeometry) → 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 error() on the returned geometry.
-
intersects
(self, rectangle: QgsRectangle) → bool¶ Returns true if this geometry exactly intersects with a
rectangle
. This test is exact and can be slow for complex geometries.The GEOS library is used to perform the intersection test. Geometries which are not valid may return incorrect results.
See also
intersects(self, geometry: QgsGeometry) -> bool Returns true if this geometry exactly intersects with another
geometry
. This test is exact and can be slow for complex geometries.The GEOS library is used to perform the intersection test. Geometries which are not valid may return incorrect results.
See also
-
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 return true for isEmpty().
See also
-
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.
-
isGeosValid
(self, flags: Union[QgsGeometry.ValidityFlags, QgsGeometry.ValidityFlag] = 0) → 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.
-
isMultipart
(self) → bool¶ Returns true if WKB of the geometry is of WKBMulti* type
-
isNull
(self) → bool¶ Returns true if the geometry is null (ie, contains no underlying geometry accessible via geometry() ).
See also
See also
New in version 2.10.
-
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.
-
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.
-
length
(self) → float¶ Returns the length of geometry using GEOS
New in version 1.5.
-
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 – point to seek proximity to
- 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 – geometry that should not be intersect
- Returns
difference geometry, or empty geometry if difference could not be calculated
New in version 3.0.
-
makeValid
(self) → 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 error() on the returned geometry.
- Returns
new valid QgsGeometry or null geometry on error
Note
Ported from PostGIS ST_MakeValid() and it should return equivalent results.
New in version 3.0.
-
mapToPixel
(self, mtp: QgsMapToPixel)¶ Transforms the geometry from map units to pixels in place.
- Parameters
mtp – 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.
- 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
radius – Radius of the minimal enclosing circle returned
segments – Number of segments used to segment geometry.
QgsEllipse.toPolygon()
- Returns
the minimal enclosing circle as a QGIS geometry
center: Center of the minimal enclosing circle returneds
New in version 3.0.
-
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 geometry
moveVertex(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. Returns false if atVertex does not correspond to a valid vertex on this geometry
-
nearestPoint
(self, other: QgsGeometry) → QgsGeometry¶ Returns the nearest point on this geometry to another geometry.
See also
New in version 2.14.
-
offsetCurve
(self, distance: float, segments: int, joinStyle: QgsGeometry.JoinStyle, miterLimit: float) → QgsGeometry¶ Returns an offset line at a given distance and side from an input line.
- Parameters
distance – buffer distance
segments – for round joins, number of segments to approximate quarter-circle
joinStyle – join style for corners in geometry
miterLimit – limit on the miter ratio used for very sharp corners (JoinStyleMiter only)
New in version 2.4.
-
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.
See also
New in version 3.0.
-
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.
-
overlaps
(self, geometry: QgsGeometry) → bool¶ Test for if geometry overlaps another (uses GEOS)
New in version 1.5.
-
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.
-
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 error() on the returned geometry.
See also
See also
-
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.
-
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 call unaryUnion() on the set of input geometries and then pass the result to polygonize(). An empty geometry will be returned in the case of errors.New in version 3.0.
-
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
is true, then the z values are also tested and nodes with the same x and y but different z will be maintained.Note that duplicate nodes are not tested between different parts of a multipart geometry. E.g. a multipoint geometry with overlapping points will not be changed by this method.
The function will return true if nodes were removed, or false if no duplicate nodes were found.
New in version 3.0.
-
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.
-
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.
-
reshapeGeometry
(self, reshapeLineString: QgsLineString) → QgsGeometry.OperationResult¶ Replaces a part of this geometry with another line
- Returns
OperationResult a result code: success or reason of failure
-
rotate
(self, rotation: float, center: QgsPointXY) → QgsGeometry.OperationResult¶ Rotate this geometry around the Z axis
- Parameters
rotation – clockwise rotation in degrees
center – rotation center
- Returns
OperationResult a result code: success or reason of failure
-
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.
-
shortestLine
(self, other: QgsGeometry) → QgsGeometry¶ Returns the shortest line joining this geometry to another geometry.
See also
New in version 2.14.
-
simplify
(self, tolerance: float) → QgsGeometry¶ Returns a simplified version of this geometry using a specified tolerance value
-
singleSidedBuffer
(self, distance: float, segments: int, side: QgsGeometry.BufferSide, joinStyle: QgsGeometry.JoinStyle = QgsGeometry.JoinStyleRound, 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 – buffer distance
segments – for round joins, number of segments to approximate quarter-circle
side – side of geometry to buffer
joinStyle – join style for corners
miterLimit – limit on the miter ratio used for very sharp corners
- Returns
buffered geometry, or an empty geometry if buffer could not be calculated
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 – number of smoothing iterations to run. More iterations results in a smoother geometry
offset – fraction of line to create new vertices along, between 0 and 1.0, e.g., the default value of 0.25 will create new vertices 25% and 75% along each line segment of the geometry for each iteration. Smaller values result in “tighter” smoothing.
minimumDistance – minimum segment length to apply smoothing to
maxAngle – maximum angle at node (0-180) at which smoothing will be applied
New in version 2.9.
-
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 – Horizontal spacing of the grid (x axis). 0 to disable.
vSpacing – Vertical spacing of the grid (y axis). 0 to disable.
dSpacing – Depth spacing of the grid (z axis). 0 (default) to disable.
mSpacing – Custom dimension spacing of the grid (m axis). 0 (default) to disable.
New in version 3.0.
-
splitGeometry
(self, splitLine: Iterable[QgsPointXY], topological: bool) → Tuple[QgsGeometry.OperationResult, List[QgsGeometry], List[QgsPointXY]]¶ Splits this geometry according to a given line.
- Parameters
splitLine – the line that splits the geometry
param[out] newGeometries list of new geometries that have been created with the split :param topological: true if topological editing is enabled param[out] topologyTestPoints points that need to be tested for topological completeness in the dataset
- Returns
OperationResult a result code: success or reason of failure
-
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))
-
staticMetaObject
= <PyQt5.QtCore.QMetaObject object>¶
-
subdivide
(self, maxNodes: int = 256) → 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 error() on the returned geometry.
New in version 3.0.
-
symDifference
(self, geometry: QgsGeometry) → 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 error() on the returned geometry.
-
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 unlike buffer() 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.
-
touches
(self, geometry: QgsGeometry) → bool¶ Test for if geometry touch another (uses GEOS)
New in version 1.5.
-
transform
(self, ct: QgsCoordinateTransform, direction: QgsCoordinateTransform.TransformDirection = QgsCoordinateTransform.ForwardTransform, transformZ: bool = False) → QgsGeometry.OperationResult¶ Transforms this geometry as described by the coordinate transform
ct
.The transformation defaults to a forward transform, but the direction can be swapped by setting the
direction
argument.By default, z-coordinates are not transformed, even if the coordinate transform includes a vertical datum transformation. To transform z-coordinates, set
transformZ
to true. This requires that the z coordinates in the geometry represent height relative to the vertical datum of the source CRS (generally ellipsoidal heights) and are expressed in its vertical units (generally meters).- Returns
OperationResult a result code: success or reason of failure
transform(self, t: QTransform, zTranslate: float = 0, zScale: float = 1, mTranslate: float = 0, mScale: float = 1) -> QgsGeometry.OperationResult 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
.- Returns
OperationResult a result code: success or reason of failure
-
translate
(self, dx: float, dy: float, dz: float = 0, dm: float = 0) → QgsGeometry.OperationResult¶ Translates this geometry by dx, dy, dz and dm.
- Returns
OperationResult a result code: success or reason of failure
-
type
(self) → QgsWkbTypes.GeometryType¶ Returns type of the geometry as a QgsWkbTypes.GeometryType
See also
-
unaryUnion
(geometries: Iterable[QgsGeometry]) → 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.
-
validateGeometry
(self, method: QgsGeometry.ValidationMethod = QgsGeometry.ValidatorQgisInternal, flags: Union[QgsGeometry.ValidityFlags, QgsGeometry.ValidityFlag] = 0) → 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.
-
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.
-
vertexAt
(self, atVertex: int) → QgsPoint¶ Returns coordinates of a vertex.
- Parameters
atVertex – index of the vertex
- Returns
Coordinates of the vertex or QgsPoint(0,0) on error
-
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.
-
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.
-
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.
-
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
is true than line string boundary geometries will be returned instead of polygons. An empty geometry will be returned if the diagram could not be calculated.New in version 3.0.
-
within
(self, geometry: QgsGeometry) → bool¶ Test for if geometry is within another (uses GEOS)
New in version 1.5.
-