Assigning Directory Listings to Counties With Point-in-Polygon
A Google Maps export gives you an address and, usually, a latitude and longitude for each business. What it does not reliably give you is the county. If your directory has county pages, you need that field, and guessing
A Google Maps export gives you an address and, usually, a latitude and longitude for each business. What it does not reliably give you is the county. If your directory has county pages, you need that field, and guessing it from the city name breaks in more places than you would expect. Cities cross county lines, mailing addresses use a nearby town's name, and unincorporated areas have no city at all.
The fix is a point-in-polygon join. Take each listing's coordinates, find which county boundary contains that point, and write the county onto the row. This post walks through doing that in Python as part of a static directory build, along with the edge cases that come up with real exports.
Get the boundary files
The US Census Bureau publishes county boundaries in two main forms. TIGER/Line shapefiles are the detailed version. Cartographic boundary files are generalized, smaller versions made for mapping. For assigning businesses to counties the cartographic files are usually precise enough and load much faster, though points very close to a boundary can land differently depending on which file you use.
Both include state and county FIPS codes for each county, plus the county name. Keep the FIPS code in your data. County names repeat across states (there are many Washington Counties), and the five-digit code is a cleaner key for joins and internal lookups.
Check your coordinates first
Before any spatial work, look at the latitude and longitude columns. Common problems in exports:
- Missing coordinates on some rows.
- Latitude and longitude swapped.
- Coordinates stored as text with stray characters.
- Service-area businesses with no public address, whose coordinates may point to a rough area instead of a building.
Drop or flag rows without usable coordinates. A quick sanity check is to confirm every point falls inside the bounding box of your target state. Anything outside is probably swapped or wrong.
Do the join
GeoPandas keeps this short. Load the export, turn the coordinates into points, load the county file and join:
import pandas as pd
import geopandas as gpd
df = pd.read_csv("export.csv").dropna(subset=["latitude", "longitude"])
pts = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longitude, df.latitude), crs="EPSG:4326")
counties = gpd.read_file("county_boundaries.zip").to_crs("EPSG:4326")
joined = gpd.sjoin(pts, counties[["GEOID", "NAME", "geometry"]], how="left", predicate="within")
joined = joined.rename(columns={"GEOID": "county_fips", "NAME": "county"})
joined.drop(columns=["geometry", "index_right"]).to_csv("export_with_county.csv", index=False)
Watch the coordinate order. points_from_xy takes x first, which is longitude. Getting that backwards is the usual reason every point ends up in the ocean.
Reproject the county file to match the points before joining. Census boundary files use a geographic coordinate system based on NAD83, while export coordinates are WGS84. At county scale the difference is tiny, but matching them explicitly avoids warnings and surprises.
Handle the edge cases
After the join, look at the rows that did not match. They usually fall into a few groups. Some are outside your state and should be dropped. Some sit right on a boundary, along a river or road that marks the county line. Some are on water, such as a marina or a waterfront restaurant whose point lands just past the shoreline in a generalized file.
For boundary and water cases, a nearest-polygon fallback works well: for each unmatched point, take the closest county within a small distance. Do this in a projected coordinate system measured in meters, so the distance threshold means something. Log every fallback assignment so you can check it later.
Use the result in the build
Once each row has a county FIPS code and name, the rest is template work. Group listings by county to build county pages, link each county page to its city pages, and add the county to each listing's breadcrumb. Build URL slugs from the county and state names, and keep the FIPS code as the internal key so two counties with the same name never collide.
Think about the next export, too. New businesses need the same join, so make it a step in the build pipeline instead of a one-off script. Boundary files change rarely, but the Census Bureau releases new vintages, so refreshing yours every year or so is sensible.
If you are planning the pages themselves, a beginner's guide to county pages in a local directory covers what a county page should say and how it relates to city pages. For more on scraping, cleaning and refreshing listing data, see the Google Maps listing data guides.
Questions about county assignment
Can I use the city name instead of coordinates?
For a rough first pass in a small area, maybe. It fails for cities that span counties, mailing names that differ from the actual municipality, and unincorporated areas. Coordinates avoid all of that.
What about listings with only a service area?
Their coordinates may be approximate. Assign them by the point you have, flag them, and consider presenting them on the county page as serving the area instead of being located in a particular city.
Do I need GeoPandas for this?
No. Shapely alone can test points against polygons, and a database with spatial support can run the same join in SQL. GeoPandas is simply the shortest path for a CSV-based build. 1 Click Directory Builder turns a Google Maps export into a complete directory site with county and city pages; if you are building your own pipeline instead, this join is the piece that makes county pages possible.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.