I have a criteria to select the features from a layer that overlap the features of another layer, but i do not know how to copy the fields at the same time: Tyhe code does: - two layers (1 and 2) of polygons - if one feature of polygon2 overlap more than 80% one of polygon1, it selects it.
How to also copy the fields of polygon1 to add them to the fields of the selected polygon2?
from qgis.core import *
import processing
import os
mapcanvas = iface.mapCanvas()
layers = mapcanvas.layers()
#polygon1
feats_lyr1 = [ feat for feat in layers[0].getFeatures() ]
#polygon2
feats_lyr2 = [ feat for feat in layers[1].getFeatures() ]
selected_feats = []
for i, feat1 in enumerate(feats_lyr1):
for j, feat2 in enumerate(feats_lyr2):
if feat1.geometry().intersects(feat2.geometry()):
area1 = feat1.geometry().intersection(feat2.geometry()).area()
area2 = feat2.geometry().area()
crit =area1/area2
if crit > 0.8:
selected_feats.append(feat2)
epsg = layers[0].crs().postgisSrid()
uri = "Polygon?crs=epsg:" + str(epsg) + "&index=yes"
mem_layer = QgsVectorLayer(uri,
"mem_layer",
"memory")
for i, feat in enumerate(selected_feats):
feat.setAttributes(selected_feats[i].attributes())
prov = mem_layer.dataProvider()
attr = layers[1].dataProvider().fields().toList()
prov.addAttributes(attr)
mem_layer.updateFields()
prov.addFeatures(selected_feats)
QgsMapLayerRegistry.instance().addMapLayer(mem_layer)