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 *

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:


layer = QgsVectorLayer('Polygon', 'Intersect' , 'memory')
prov = layer.dataProvider()
feat = QgsFeature()

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:


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.

  • 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. – Maximilien jaffrès Jan 16 '19 at 10:34
  • Try changing you output layer type of MULTIPOLYGON rather than polygon. – Ahsan Mukhtar Jan 16 '19 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 Jan 16 '19 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() – Maximilien jaffrès Jan 16 '19 at 12:11
  • Using the python method tells me that, unexpectedly, the polygon was valid. Despite this, buffering did solve the issue. – Erik Jan 16 '19 at 13:41

Your Answer

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

Browse other questions tagged or ask your own question.