[GIS] How to get the polygon vs. Polygon Intersection Coordinates using python

pyqgisqgis-2

I want to find the intersection coordinates between two polygons.

aLayer = canvas.currentLayer()
selection = aLayer.selectedFeatures()
for geom1,geom2 in itertools.permutations(selection,r=2):
    intersect=geom1.geometry().intersection(geom2.geometry())
    intersect_list=intersect.asPolyline()
    count=len(intersect_list)

Its giving the intersection geometry but when i am converting that as a polyline to get the intersection vertices it is giving empty list. Here what i am doing wrong.

Best Answer

You need to consider the different possibilities for the geometry of polygon features intersection. Options could be a point, line or polygon. However, it is preferable to express the geometry directly as WKT because the code is more concise and it is easier to get a memory layer.

To try out my approach, first, I modified your code to:

import itertools

canvas = iface.mapCanvas()

aLayer = canvas.currentLayer()
selection = aLayer.selectedFeatures()
n=len(selection)
list = range(n)

for i,j in itertools.combinations(list, 2):
    geom = selection[i].geometry().intersection(selection[j].geometry())
    print geom.exportToWkt()

After running it with a two features shapefile, where the intersection is a polygon, I got:`

enter image description here

I used the QuickWKT plugin to put the polygon layer visible at the Map Canvas.

At the next situation, the features are adjacent and the intersection is a LineString; where the QuickWKT plugin was also used to visualize the line layer at the Map View.

enter image description here

I hope that it helps.

Related Question