I'm trying to intersect two polygons with intersection() function of QgsGeometry. The problem is that the result is a multipart polygon instead a single part polygon and QGIS doesn't allow me to save the output layer.
The output layer needs to be a Polygon, not Multipolygon.
I need to work at geometry level, I followed this topic but the problem already exist.
This is my python code:
l1_list = QgsProject.instance().mapLayersByName('Buffer_10km')
l2_list = QgsProject.instance().mapLayersByName('municipality')
l1 = l1_list[0]
l2 = l2_list[0]
prv1 = l1.dataProvider()
prv2 = l2.dataProvider()
# Create a memory layer to store the result
outlayer = QgsVectorLayer('Polygon?crs=' + prv1.crs().toWkt(), "result", "memory")
outpr = outlayer.dataProvider()
feats_l1 = l1.getFeatures()
list_geom_l1 = []
for feat_l1 in feats_l1:
print('id feature: ' + str(feat_l1.id()))
g_l1 = feat_l1.geometry()
list_geom_l1.append(g_l1)
outlayer.startEditing()
outlayer. dataProvider().addAttributes([QgsField('code', QVariant.String)])
for feature in prv2.getFeatures():
g = feature.geometry()
g_tmp = g.intersection(list_geom_l1[0])
print('Multipart?: ' + str(g_tmp.isMultipart()))
new_feat = QgsFeature()
new_feat.setGeometry(g_tmp)
outlayer.addFeature(new_feat)
outlayer.commitChanges()
outlayer.updateExtents()
QgsProject.instance().addMapLayer(outlayer)
The reference system of input layers are the same (WGS84). Below there is an image of the layers.
