3

I'd like to compare geometries using DE-9IM patterns in my QGIS plugin written in Python. I've tried to instantiate QgsGeos but it seems there's no such module in qgis.core, as reported by the following Python exception :

> from qgis.core import QgsGeos
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ImportError: cannot import name QgsGeos

I could also use shapely but I don't know if this module is included in all QGIS distributions.

Any suggestion ?

3 Answers 3

5

I've just found what I think is the good way to instantiate a QgsGeometryEngine (QgsGeos is a subclass of QgsGeometryEngine) :

my_geometry_engine = QgsGeometry.createGeometryEngine(a_geometry)

(see https://qgis.org/api/classQgsGeometry.html#a9d16b0eca18cf3a965d1a27e0b680004)

1
  • How would you run this on a layer to check if each polygon in the layer is contained within another polygon in the same layer? Jun 16, 2021 at 14:17
3

There's now a function called relate implemented in the expression editor which gives the DE-9IM matrix... just stumbled across it recently. I suspect it's fairly new, maybe new to 2.16?

QGIS relate function

You might want to look at the QgsExpression class - not tried this myself but it looks like that might be a way to do this.

2
  • Thank you for your answer. I've seen this but I have not yet found how to process geometries with QgsExpression.
    – bchartier
    Aug 19, 2016 at 10:21
  • I've just read the QgsExpression documentation. It would be a great solution if I wanted to evaluate expressions against features. In my case, I only have geometries (at this step of my process). Thank you again.
    – bchartier
    Aug 19, 2016 at 10:25
0

This works for me in Python console of QGIS 2.18.13. A bit hacky though.

a = QgsGeometry.fromWkt('LINESTRING(40 40,120 120)')
b = QgsGeometry.fromWkt('LINESTRING(40 40,60 120)')

assert(isinstance(a, QgsGeometry))
assert(isinstance(b, QgsGeometry))

expr = QgsExpression("relate( geom_from_wkt( '{0}' ), geom_from_wkt( '{1}' ) )".format(a.exportToWkt(), b.exportToWkt()))
print(expr.expression())
print(expr.evaluate())

Outputs:

u"relate( geom_from_wkt( 'LineString (40 40, 120 120)' ), geom_from_wkt( 'LineString (40 40, 60 120)' ) )"
u'FF1F00102'

See also:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.