3

I have two polygons in different layers. I am trying to find the intersect between the two polygons. Below a figure showing my test case. I initially wanted to find the intersect between the green polygon and a bunch of other polygons and wrote a code for that. For all but one polygon this functioned as expected, shown below is the one polygon for which my function fails. The two polygons for which I'm trying to find the intersect

My code:

from qgis.core import *
from PyQt4.QtCore import *

layer1=None
layer2=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
    if lyr.name() =='Poly':
        layer1 = lyr
    if lyr.name() =='Buffer':
        layer2 = lyr

features1 = layer1.getFeatures()
features2 = layer2.getFeatures()

for feature1 in features1:
    for feature2 in features2:
        geominter=feature1.geometry().intersection(feature2.geometry())

print(geominter.area())
print(geominter.asPolygon())

layer = QgsVectorLayer('Polygon', 'Intersect' , 'memory')
prov = layer.dataProvider()
layer.startEditing()
feat = QgsFeature()
feat.setGeometry(geominter)
prov.addFeatures([feat])
layer.commitChanges()
layer.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([layer])
layer.triggerRepaint()

This code worked for all other polygons I needed to find the intersect for except this one. The output layer contains one element (as expected) but nothing is plotted. The print outputs of this code are:

30.2517066088
[]

It accurately computes the area of the polygon I expect to obtain but the .asPolygon() output is empty, which I expect is why nothing is plotted. What could be the reason for this, and how can I obtain the intersect between these two polygons?

I am using QGIS version 2.18.11 on Windows 8.

5
  • Hi and welcome, did you check if your troublesome polygon is valid ? If not it may be the problem. Then you should try to make it valid with a buffer for exemple. Commented Jan 16, 2019 at 10:34
  • Try changing you output layer type of MULTIPOLYGON rather than polygon. Commented Jan 16, 2019 at 11:00
  • I wasn't sure how to check if my polygon was valid or not. However adding a small (but non-zero) buffer did solve the problem. @Maximilienjaffrès Thank you very much
    – Erik
    Commented Jan 16, 2019 at 11:26
  • it was probably a non valid geometry problem, the buffer solved it. if you want to test the validity look for the Qgis tool : Vector > Geometry Tools > Check Geometry Validity or use python method geom.isGeosValid() Commented Jan 16, 2019 at 12:11
  • Using the python method tells me that, unexpectedly, the polygon was valid. Despite this, buffering did solve the issue.
    – Erik
    Commented Jan 16, 2019 at 13:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.