QGIS – How to List Names of Overlapping Polygons in QGIS

layersoverlapping-featurespolygonqgis

In QGIS, I would like to assign polygons in one layer (ZIP codes) to polygons in another layer (counties). Specifically, I would like to know, for each ZIP code, in which county it is located. In case a ZIP code overlaps with multiple counties, I would like to pick the county for a ZIP code that contains the largest share of the ZIP codes' area.

I tried the "Overlap Analysis" tool, which already gets me very close: In the resulting attribute table I find, for each ZIP Code, the overlapping area between the ZIP code and the county as well as the percentage of the ZIP code's area that overlaps with the county. Crucially, however, I am missing the name of the county. What am I doing wrong?

Best Answer

On the ZIP layer, use this expression to get the name of the county polygon with the largest intersection:

array_max (
    array_foreach (
        overlay_intersects('county', $id),
        if (
            area (
                intersection (
                    $geometry, 
                    geometry (get_feature_by_id ('county', @element))
                )
            ) = 
            array_max (
                array_foreach (
                    overlay_intersects('county', $id),
                    area (
                        intersection (
                            $geometry, 
                            geometry (get_feature_by_id ('county', @element))
                        )
                    )
                )
            ),
            attribute (get_feature_by_id ('county', @element),'name'),
            ''
        )
    )
)

Blue label is generated as a dynamic label with the expression from above:

enter image description here

Related Question