Given 2 polygon layers. The features of the first one should receive the attributes of this feature of the second one, which has the largest overlap area.
The following Python script loops over both feature sets (brute force). If there is an overlap, it assignes the attributes if the overlap area is larger than the previous.
Spatial indexing and preselection with spatial filtering may enhance the execution speed.
# get layers
grid_lyr = QgsMapLayerRegistry.instance().mapLayersByName('grid')[0]
poly_lyr = QgsMapLayerRegistry.instance().mapLayersByName('community')[0]
# get field definitions
fields = poly_lyr.fields()
# create result layer
res_lyr = QgsVectorLayer('Polygon?crs=EPSG:4326', 'result', 'memory')
res_prov = res_lyr.dataProvider()
res_prov.addAttributes(fields)
res_lyr.updateFields()
# holds the attributes to update with
attributes = []
feats = []
# loop over grid features
for g in grid_lyr.getFeatures():
overlap_area = -9999
# loop over the features to assign to, if they overlap
for poly in poly_lyr.getFeatures():
# build overlap geometry
overlap = g.geometry().intersection(poly.geometry())
# if geometries overlap
if not overlap.isEmpty():
# and if overlap is larger than the previous one
if overlap_area < overlap.area():
overlap_area = overlap.area()
# remember attributes
attributes = poly.attributes()
# create new feature
feat = QgsFeature(fields)
feat.setGeometry(g.geometry())
feat.setAttributes(attributes)
feats.append(feat)
# finally add features to result layer and display it
res_prov.addFeatures(feats)
QgsMapLayerRegistry.instance().addMapLayer(res_lyr)
The test case:
