I have a buffer that intersects with two polygons.

enter image description here

How can displace the buffer to the polygon with the largest intersection?

In addition

enter image description here

So far my code determines how many polygons my buffer intersects with, counts them, and adds them to a field called "NUMPOLYGON"

layer1 = QgsProject.instance().mapLayersByName("MERGE_PARCELAS")[0]

layer2 = QgsProject.instance().mapLayersByName("Polygon_sv")[0]
caps = layer2.dataProvider().capabilities()

if caps & QgsVectorDataProvider.AddAttributes:
    res = layer2.dataProvider().addAttributes([QgsField("NUMPOLYGON", QVariant.Int)])



for feat in layer2.getFeatures():
    feat['NUMPOLYGON'] = 0



for f in layer2.getFeatures():
    for j in layer1.getFeatures():
        if f.geometry().intersects(j.geometry()):
            if f['NUMPOLYGON'] != NULL:
                f['NUMPOLYGON'] += 1

once the values ​​greater than one have been identified.


1 Answer 1


Try this approach, it will move the small feature to the largest overlapping features centroid:

def nameToLyr(layername):
    """Outputs a layer from a layername input"""
    return QgsProject.instance().mapLayersByName(layername)[0]

def giveCentroidCoords(afeature):
    """Return x as y coordinates of a features centroid"""
    cent = afeature.geometry().centroid().asPoint()
    return (cent.x(), cent.y())

#Create layers
buffL = nameToLyr('buff')
largeL = nameToLyr('largelayer')

largeFeats = [f for f in largeL.getFeatures()] #List all large features

geometryMap = {} #A dictionary to hold each bufferlayers feature id and new geometry

for bfeat in buffL.getFeatures(): #For each bufferfeatures
    intersecting = [LF for LF in largeFeats if LF.geometry().intersects(bfeat.geometry())] #Find all intersecting features in large layer
    biggest = max(intersecting, key=lambda x: x.geometry().intersection(bfeat.geometry()).area()) #Find the one with the largest intersection area
    toX, toY = giveCentroidCoords(biggest) #Find the centroid coordinates of the largest overlapping feature
    fromX, fromY = giveCentroidCoords(bfeat) #Find the centroid coordinates of the buffer feature
    deltaX = toX-fromX #Calculate how much to move the buffer features in X direction
    deltaY = toY-fromY
    newgeom = bfeat.geometry() #Fetch its geometry
    newgeom.translate(deltaX, deltaY) #Move it
    geometryMap[bfeat.id()] = newgeom #Store it in the dictionary

buffL.dataProvider().changeGeometryValues(geometryMap) #Change the values
iface.mapCanvas().redrawAllLayers() #Redraw

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.