4

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?

1 Answer 1

4

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

1
  • 2
    Thanks so much, works like a charm! Two remarks for people who are new to QGIS: 1) Using the above-mentioned code to generate a new field in the attribute table yields an attribute (rather than a label) for each ZIP code. 2) Running the code requires a QGIS version newer than 3.18.
    – Financeguy
    Feb 4, 2022 at 11:02

Your Answer

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

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