DEV Community

Cover image for The ZIP Already Knows the City: Autofill City and State, Then Check the Address
Casey Rivers for Geoapify Maps API

Posted on

The ZIP Already Knows the City: Autofill City and State, Then Check the Address

Most US checkout forms ask for the city and the state, and then for the ZIP code. But the five digits of the ZIP already tell you both. Asking for them again is three fields of typing, and three chances for a typo.

In this tutorial we turn it around: the user starts with the ZIP code, picks it from a short list, and city and state fill in. Then a "Check the address" button geocodes the finished address and tells you how sure the match is, and whether a house was found at all. At the end, we ask an AI coding assistant to build the same form.

TL;DR

  • Make the ZIP field an autocomplete that searches only US postcodes: type: "postcode" and filter: { countrycode: ["us"] } in @geoapify/geocoder-autocomplete. Picking a ZIP gives you city and state_code.
  • Typing "0213" lists Boston ZIP codes. Four keys, a pick, and three fields are done.
  • To check the finished address, send it to the Geocoding API and read rank.confidence. A street typo ("Avn") drops it to 0.63, a city typo ("Seatle") to 0.90.
  • Confidence alone isn't enough: an address without a house number still gets 1.00. result_type tells you a street was found, not a house.
  • A vague prompt to an AI assistant got a good approach with a stale-data bug. A precise one got our demo.

๐Ÿ‘‰ Live demo: type a few digits of a ZIP code, pick one, add a street and press "Check the address".


Table of Contents

  1. What we're building
  2. What a confidence score can and can't tell you
  3. Step 1: A ZIP field that suggests US postcodes only
  4. Step 2: Fill city and state
  5. Step 3: Check the address
  6. Let an AI assistant write it
  7. Summary
  8. FAQ

What we're building

A shipping-address form in the "ZIP first" order: ZIP code, City and State on the first row, Street below. The cursor starts in the ZIP field.

Left: typing 0213 in the ZIP field lists 02133, 02130, 02131 and 02132, all Boston, MA. Right: ZIP 98103 picked, City Seattle and State WA filled in, street 3601 Fremont Ave N typed, and the address check showing Looks good with confidence 1.00

Type "0213", and the list shows Boston ZIP codes as "02133 ยท Boston, MA". Pick one with the mouse, or with โ†“ and Enter. City and State fill in, the cursor moves to Street, and every field stays editable.

What a confidence score can and can't tell you

The ZIP gives you city and state, but the street is still typed by hand. That's where a check helps. The Geocoding API finds the address and rates the match with rank.confidence, from 0 to 1.

We sent one Seattle address in several versions:

Table of live Geocoding API results for 3601 Fremont Ave N, Seattle, WA 98103 typed six ways: correct and written out both 1.00; street typo Avn 0.63; city typo Seatle 0.90; no house number result_type street with confidence 1.00; no street result_type postcode with 1.00

Typed (Seattle, WA 98103) result_type confidence street level city level
3601 Fremont Ave N building 1.00 1.00 1.00
3601 Fremont Avenue North building 1.00 1.00 1.00
3601 Fremont Avn N building 0.63 0.63 1.00
3601 Fremont Ave N, Seatle building 0.90 0.90 1.00
Fremont Ave N (no house number) street 1.00 1.00 1.00
(no street) postcode 1.00 โ€” 1.00

Three things to take from it:

  • Typos lower the confidence, but the right address is still found. Both typo rows found 3601 Fremont Avenue North. A low value means "take a second look", not "wrong".
  • Abbreviations don't matter. "Ave N" and "Avenue North" both score 1.00.
  • A missing house number doesn't lower the confidence. The street was matched perfectly, so it's 1.00. Only result_type shows that you got a street, not a house.

So the check needs both: confidence for "how sure", result_type for "what was found".

Step 1: A ZIP field that suggests US postcodes only

We use the @geoapify/geocoder-autocomplete library. It creates its own input inside a container and calls the Address Autocomplete API as the user types.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@geoapify/geocoder-autocomplete@3.1.0/styles/round-borders.css">
<script src="https://cdn.jsdelivr.net/npm/@geoapify/geocoder-autocomplete@3.1.0/dist/index.min.js"></script>

<label for="zip-field">ZIP code</label>
<div id="zip-field" class="autocomplete-container"></div>
Enter fullscreen mode Exit fullscreen mode
const zipField = new autocomplete.GeocoderAutocomplete(
  document.getElementById("zip-field"),
  "YOUR_API_KEY",
  {
    type: "postcode",                 // suggest postcodes only
    filter: { countrycode: ["us"] },  // only in the US
    limit: 5,
    placeholder: "e.g. 02134",
    skipIcons: true,
    skipSelectionOnArrowKey: true     // arrows highlight, Enter selects
  }
);

// Suggestion text: "02134 ยท Boston, MA" instead of the full formatted address
zipField.setPostprocessHook((feature) => {
  const p = feature.properties;
  return `${p.postcode} ยท ${p.city || p.county || ""}, ${p.state_code}`;
});

// Start with the ZIP code
document.querySelector("#zip-field input").focus();
Enter fullscreen mode Exit fullscreen mode
Option Value Why
type "postcode" the list shows ZIP codes, not streets or places
filter { countrycode: ["us"] } "10001" means New York, not a postcode in another country
limit 5 a short list; the user types one more digit to narrow it
skipSelectionOnArrowKey true see below

skipSelectionOnArrowKey saved us a bug. By default, every โ†“ press selects the highlighted suggestion and fires select. Our select handler moves the cursor to Street, so the second โ†“ press landed in the Street field. With the option on, arrows only highlight, and Enter selects.

Two layout details: the container needs position: relative so the list opens under the input. And style your own inputs with a selector that doesn't match the library's input (here .field > input). Otherwise your padding wins and the library's clear (ร—) button ends up outside the field.

Step 2: Fill city and state

When the user picks a ZIP, the library fires select with the postcode as a GeoJSON feature:

zipField.on("select", (feature) => {
  if (!feature) return; // the field was cleared: keep city and state

  const p = feature.properties;

  zipField.setValue(p.postcode); // the ZIP field shows only "98103"
  cityInput.value = p.city || "";
  stateInput.value = p.state_code || "";

  if (p.city) {
    streetInput.focus();
  } else {
    cityInput.focus(); // no city in the result: let the user type it
  }
});
Enter fullscreen mode Exit fullscreen mode
  • setValue replaces the input text without a new request. Without it, the field would keep the long suggestion text.
  • state_code is the two-letter code (WA) that US forms expect. state has the full name.
  • A result can come without a city. Then City stays empty and gets the focus. Don't put the county into City instead: a county isn't a mailing city.

Step 3: Check the address

The button sends the full address as one line to the Geocoding API:

https://api.geoapify.com/v1/geocode/search?text=3601%20Fremont%20Ave%20N%2C%20Seattle%2C%20WA%2098103&filter=countrycode:us&limit=1&format=json&apiKey=YOUR_API_KEY
Enter fullscreen mode Exit fullscreen mode
Parameter Value Meaning
text street, city, state ZIP the whole address as typed
filter countrycode:us search the US only
limit 1 the best match is enough
format json plain JSON with a results array

Then it reads the best match:

const GOOD_CONFIDENCE = 0.8; // each app picks its own threshold

function checkAddress() {
  const params = new URLSearchParams({
    text: `${street}, ${city}, ${state} ${zip}`,
    filter: "countrycode:us",
    limit: 1,
    format: "json",
    apiKey: "YOUR_API_KEY"
  });

  fetch(`https://api.geoapify.com/v1/geocode/search?${params}`)
    .then((response) => response.json())
    .then((data) => {
      const found = data.results[0];
      if (!found) return showResult("review", "No match found.");

      // a house was found, not only a street or a postcode
      const foundHouse = ["building", "amenity"].includes(found.result_type);
      const good = found.rank.confidence >= GOOD_CONFIDENCE && foundHouse;

      showResult(good ? "good" : "review", found);
    });
}
Enter fullscreen mode Exit fullscreen mode

Three address check results: 3601 Fremont Ave N Looks good with confidence 1.00; 3601 Fremont Avn N Needs review with 0.63; Fremont Ave N Needs review: found a street, not a house, with 1.00

  • 0.8 is a starting point, not a rule. A shipping form can be stricter than a newsletter sign-up.
  • "Needs review", not "invalid". The user may be right and the map data incomplete, for example a new building. The demo never overwrites what the user typed; it shows what it found and lets them decide.
  • The API also returns confidence_street_level and confidence_city_level, so you can say which part looks off. See the confidence section of the docs.

Let an AI assistant write it

We gave the task to an AI coding assistant (Claude) twice, each time in a fresh session without web access, and ran both pages with a real API key.

Prompt 1, vague:

Add a ZIP code field to my checkout form that fills in city and state, using Geoapify. Give me one HTML file I can open in the browser.

Page written by an AI assistant from the vague prompt: after ZIP 98103, typing 00000 shows "ZIP code not found" while City still says Seattle and State WA; notes: works, checks the ZIP, stale values, county as city

A sensible design: no library, one request to the Geocoding API with type=postcode once the field holds 5 digits, and a check that the returned postcode equals the typed one. 98103 filled Seattle, WA. But:

  • Stale values. After 98103, we typed 00000. The page said "ZIP code not found", and Seattle, WA stayed in the form. Clear the fields when a lookup fails.
  • County as city. When a result has no city, its fallback chain ends with county and writes the county name into City.
  • The user can't see what will be filled until it's filled. There's no list to choose from.

Prompt 2, precise: we described the field order, the library and version, type, filter, skipSelectionOnArrowKey, the suggestion text, setValue, the focus moves, the address check with its threshold, and the CSS trap with the clear button.

Page written by an AI assistant from the precise prompt: ZIP 98103, Seattle, WA, street 3601 Fremont Ave N and Looks good with confidence 1.00; notes: ZIP first, arrows and Enter, address check, a cosmetic font size difference

It matches our demo: the cursor starts in ZIP, the list reads "98103 ยท Seattle, WA", โ†“ and Enter work, and the check shows confidence with the 0.8 threshold. The one flaw was cosmetic: City and State used a larger font than the ZIP field.

One more thing: our prompt didn't mention result_type, and neither does the page. It says "Looks good" for an address without a house number. The assistant builds exactly the checks you name.

What made the difference:

  • Name the API mode. type: "postcode" plus a US filter turns a general search into a ZIP picker.
  • Say what happens on failure. "Clear city and state when the ZIP isn't found" is one sentence; without it, old values stay.
  • Name the library traps. skipSelectionOnArrowKey and the CSS selector came from our own bugs. One line each in the prompt.
  • Say what "valid" means. Confidence threshold and result type. An assistant won't invent the second check.

Building an AI agent instead of a form? The Geoapify MCP server gives agents geocoding tools directly, so an agent can check an address without writing the request itself.

Summary

  • Ask for the ZIP first. A postcode-only autocomplete (type: "postcode", US filter) fills city and state from one pick.
  • Use state_code for the two-letter state, setValue to keep only the ZIP in the field, and leave City empty when the result has no city.
  • Check the finished address with the Geocoding API: rank.confidence for how sure the match is, result_type for whether a house was found.
  • Show "Needs review", never "invalid", and keep what the user typed.
  • AI assistants can write this form; your prompt decides the failure handling and what counts as a good address.

FAQ

Can I fill city and state from a ZIP code without an autocomplete list?
Yes: send the 5 digits to the Geocoding API with type=postcode and filter=countrycode:us, as the AI assistant did. Check that the returned postcode equals the typed one, and clear the fields when nothing is found.

Why state_code and not state?
state_code is the two-letter code (WA, MA) that US address forms and carriers use. state is the full name ("Washington").

What confidence should I accept?
Each app decides. 0.8 is a reasonable start: typos in our test scored 0.63 and 0.90. Anything lower is worth a second look, not a rejection.

Why does an address without a house number get confidence 1.00?
Confidence rates how well the result matches what you sent. "Fremont Ave N" matches the street perfectly. Check result_type: building or amenity means a house, street or postcode means the house number is missing.

Does it work for other countries?
Yes. Change the countrycode filter (for example ["de"]) and the labels. Postcode autocomplete works the same way, but how much a postcode tells you about the city differs by country.

Should I store the corrected address or what the user typed?
Keep what the user typed, and store the geocoding result next to it if you need coordinates or a normalized form. Geoapify lets you store geocoding results; the data-source attribution comes with each result.

Why is the cursor in the ZIP field when the page opens?
So the form reads top to bottom: ZIP, then city and state appear, then the street. Users start typing without looking for the first field.


Try it

Get a free API key at myprojects.geoapify.com and try it with your own ZIP code. Does your checkout ask for the ZIP first or last? Tell us in the comments.

Top comments (0)