DEV Community

Cover image for How We Packed 51-State U.S. ZIP-Code Territory Maps Into Browser TopoJSON (Zero Map API Bills)
RickZhang
RickZhang

Posted on AI-assisted

How We Packed 51-State U.S. ZIP-Code Territory Maps Into Browser TopoJSON (Zero Map API Bills)

Building a U.S. sales territory map usually pushes you toward hosted map tiles, per-load billing, and a backend geocoder. For a spreadsheet workflow where a sales ops manager pastes 500 ZIP codes and drags regions between reps, paying per map load or uploading customer revenue tables to a third-party server is overkill.

While building MapByZip, we moved all boundary loading, spreadsheet parsing, and revenue rollups into the browser using static Census TopoJSON assets. Below are the four engineering problems that actually slowed us down and the exact setup we kept.

1. Why a single U.S. ZIP file breaks first load

There are over 33,000 U.S. ZIP Code Tabulation Areas (ZCTAs). Even after aggressive Douglas-Peucker simplification, shipping every 5-digit ZCTA polygon in one national GeoJSON or TopoJSON file creates a massive initial download and stalls mobile browsers before the first paint.

Instead of one bundle, we split our static public/geo/ directory into four separate boundary tiers:

  • us-states.topo.json (51 KB): loads immediately for the national view.
  • us-zip3.topo.json (864 KB): covers 3-digit ZIP prefix groups when teams plan regional territories.
  • us-counties.topo.json (1.15 MB): loaded only when the user switches to county level.
  • zcta/<STATE>.topo.json: 51 per-state shards ranging from 10 KB (DC) and 16 KB (DE) up to 486 KB (CA).

When a user switches to 5-digit ZIP mode, the app only fetches the state shards intersecting the current viewport or the states present in their spreadsheet, keeping a small LRU cache in memory so panning back does not re-download anything.

2. Fast ZIP lookups with a packed 1.3 MB index

Sharding polygons by state creates a lookup problem: if a user pastes 02108 or 94107, the app needs to know which state shard to fetch and where to pan the camera before downloading any geometry.

We precomputed a single zcta-index.json (1.34 MB) that stores every valid ZCTA as a compact tuple of scaled integers:

export interface PackedZctaIndex {
  bboxScale: number;
  shardStates: string[];
  zips: Record<
    string,
    readonly [
      state: string,
      county: string,
      west: number,
      south: number,
      width: number,
      height: number,
    ]
  >;
}
Enter fullscreen mode Exit fullscreen mode

Storing [west, south, width, height] as integers scaled by bboxScale cuts repeated floating-point digits out of the JSON. Unpacking it in memory takes a few milliseconds:

export function unpackZctaIndex({ bboxScale, shardStates, zips }: PackedZctaIndex) {
  const entries: Record<string, [string, string, number, number, number, number]> = {};
  for (const [zip, [state, county, west, south, width, height]] of Object.entries(zips)) {
    entries[zip] = [
      state,
      county,
      west / bboxScale,
      south / bboxScale,
      (west + width) / bboxScale,
      (south + height) / bboxScale,
    ];
  }
  return { shardStates: new Set(shardStates), zips: entries };
}
Enter fullscreen mode Exit fullscreen mode

Once unpacked, importing a CSV immediately tells us which state shards to pull, zooms the map to the union bounding box of the pasted ZIPs, and flags unknown codes without waiting on a server round-trip.

3. Spreadsheet parsing traps with U.S. ZIP codes

Clean Census geometry does not help if real Excel files fail to join against it. Four spreadsheet edge cases showed up in almost every test file:

  1. Stripped leading zeros: Excel treats 02108 (Boston) or 07030 (Hoboken) as integers and exports 2108 or 7030. When a column is mapped as a 5-digit ZIP, we left-pad 3-digit and 4-digit numeric strings back to 5 digits before lookup.
  2. ZIP+4 suffixes: CRM exports frequently output 02108-1234. Stripping the trailing four digits during normalization recovers the base ZCTA cleanly.
  3. Duplicate rows per ZIP: Sales tables usually have multiple accounts inside the same ZIP code. You have to aggregate revenue and account counts per ZIP first, then roll those totals up whenever a rep assignment changes.
  4. PO Box and unique institutional ZIPs: USPS assigns thousands of ZIP codes to PO Boxes and large buildings that have no Census ZCTA polygon. Silently dropping them breaks revenue reconciliation, so we surface every unmatched row in a review list alongside the territory totals.

4. Keeping raw customer tables in the browser

Sales ops teams hesitate to upload customer revenue spreadsheets to unknown SaaS tools. Parsing .xlsx and .csv locally in the browser keeps raw account rows in the current session, makes click-and-box-select territory rebalancing instant, and removes backend compute costs for file uploads.

If you want to inspect the live browser rendering and state-sharded ZCTA loading in action, the interactive workbench is at mapbyzip.com/zip-code-territory-map.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Rick, the number that stopped me is the 1.34 MB index sitting next to the 51 KB states tier — the lookup index costs about 26 times the national view it serves. That only matters if the index loads up front: if the app fetches zcta-index.json before the user pastes anything, the real first-load cost of the national view is 51 KB plus 1.34 MB, not 51 KB. Is the index lazy — fetched on first paste — or bundled with the initial load? If it is up front, the cheap fix is the same sharding you already did for geometry: split the index by state and fetch only the shards the pasted ZIPs need, since the packed tuples already carry the state per ZIP. Scaled integers should also compress hard under Brotli, so the served size may be far smaller than 1.34 MB — worth stating the wire size, not just the file size.

The second thing I would test is the union bounding box: a sales ops manager pasting 500 ZIPs that cluster in Boston and Phoenix gets a zoomed-out view of the whole continent, because the union of two far-apart clusters is mostly empty map. Do you zoom to the largest cluster instead, or let the manager pick? And one small one — the unmatched-row review list is the right call for PO Box ZIPs, but which Census vintage are the ZCTAs from, and what happens when a ZIP is retired or added between vintages?