Calculate distance between ZIP codes

Calculate straight-line distance between two US ZIP codes in a browser or Python, with results in miles and kilometers.

Working example

HTML + JavaScript
JavaScript (browser)

Set up ParseAPI

Use a public API key restricted to your website. Keep secret keys on your server.

Get an API key ↗

Add a distance estimate to your form

Let someone compare two US ZIP codes and see both places with their straight-line distance. Use this feature in a location form or an approximate distance comparison; it does not supply a driving route or a precise delivery boundary.

The browser renders the result directly. In Python, make the same Postal SDK call in your application's backend and pass the returned places and distances to the view.

1. Collect two ZIP strings

Keep the starting ZIP and destination as text, including leading zeroes:

HTML
<form id="distance-form">
  <div class="fields">
    <label for="from">From ZIP
      <input id="from" name="from" type="text" inputmode="numeric" pattern="[0-9]{5}" maxlength="5"
        title="Enter a five-digit US ZIP code" value="28202" required>
    </label>
    <label for="to">To ZIP
      <input id="to" name="to" type="text" inputmode="numeric" pattern="[0-9]{5}" maxlength="5"
        title="Enter a five-digit US ZIP code" value="10001" required>
    </label>
  </div>
  <button type="submit">Calculate distance</button>
  <p id="status" role="status" aria-live="polite" aria-atomic="true"></p>
</form>

Take these values from your form or request. In the browser, inputmode="numeric" offers a convenient keyboard without converting the value into a number. Check for five digits before making a request; only the lookup can tell you whether a code has usable coordinates.

Use a submit button so the person can enter both ZIPs before calculating. Keep a status message beside the inputs for loading and request failures.

2. Make one distance request

The first ZIP is the origin and the second is the destination:

JavaScript
const url = new URL(`https://api.parseapi.com/postal/${encodeURIComponent(start)}/distance/${encodeURIComponent(end)}`);
url.search = new URLSearchParams({ country: 'US', key: API_KEY });
const response = await fetch(url, { headers: { 'X-API-Version': '2.1.0' }, signal });

country=US applies to both ZIPs. The operation compares postal codes within one country. The browser encodes each code as a path segment; the SDK handles that request construction for Python.

The response includes from and to, each with a postal code and an available city name. distance is kilometers, and distance_mi is the same measurement in miles. Both units are already returned, so you need no second request or unit conversion.

Check the response before using those fields as a successful measurement. An unknown ZIP or a ZIP without coordinates needs an unavailable result, not a distance of zero.

3. Put the places and measurement on the page

JavaScript
function showDistance(data) {
  if (!data || !data.from || !data.to) {
    throw new Error('The lookup returned an unexpected response. Try again.');
  }
  // Both units are returned. Never coerce a missing value into zero.
  if (!Number.isFinite(data.distance) || data.distance < 0 || !Number.isFinite(data.distance_mi) || data.distance_mi < 0) {
    throw new Error('Distance is unavailable for these ZIPs. Try another pair.');
  }
  if ([data.from, data.to].some(place => !(place.city === null || typeof place.city === 'string'))) {
    throw new Error('The lookup returned an unexpected place label. Try again.');
  }
  const label = (place) => place.city ? `${place.postal} (${place.city})` : place.postal;
  document.querySelector('#route').textContent = `${label(data.from)} to ${label(data.to)}`;
  const formatted = data.distance_mi.toLocaleString('en-US', { maximumFractionDigits: 2 });
  document.querySelector('#distance').textContent = `${formatted} miles`;
  document.querySelector('#other-unit').textContent = `${data.distance.toLocaleString('en-US', { maximumFractionDigits: 2 })} km · approximate straight-line distance`;
  result.hidden = false;
  setStatus(`Distance calculated: ${formatted} miles in a straight line.`);
}

Render the origin and destination with the distance so the person can see which pair was compared. Keep the ZIP visible even when its city name is unknown. In browser components, insert returned labels with textContent.

The same ZIP at both ends can return zero. Check for a numeric value rather than if (distance), which would hide that valid result. Display miles or kilometers with an explicit unit; round for display while retaining the returned number for any further calculation.

If either input changes, clear the old measurement. Cancel pending work and ignore a late response for the previous pair. Keep both entered ZIPs available when the lookup fails so the person can correct or retry them.

For a backend integration, keep PARSEAPI_KEY on your server and use the returned from, to, distance, and distance_mi fields in your response or template. Missing city names remain null.

4. Check the feature's boundary cases

Swap the inputs: the labels should swap while the measurement stays the same. Use the same ZIP twice to check zero, then try an incomplete code and an unavailable lookup. The page should retain the inputs and show no stale distance as a fresh answer.

These are straight-line measurements between approximate ZIP locations. Both ZIPs need coordinates; a named postal record without a point cannot produce a distance. Use routing or address-level coordinates when you need driving distance, travel time, or an exact delivery policy. The Postal reference documents coverage and returned fields.

For a search around one ZIP, build a nearby ZIP list. To collect a place in an address form, autofill city and state.

Complete example

Use the complete implementation as a reference when adding this feature to your app. It includes the validation and failure handling around the calls above.

View and copy the complete source
zip-code-distance.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Distance between two ZIP codes</title>
  <style>
    :root { color-scheme: light dark; --bg: #fff; --ink: #152029; --muted: #5e6b75; --line: #d9e2e7; --field: #f6f9fa; --accent: #007c91; --button: #c5f6ff; --error: #b42335; }
    @media (prefers-color-scheme: dark) {
      :root:not([data-theme="light"]) { --bg: #0b1015; --ink: #eff7fa; --muted: #94a6b2; --line: #2c3942; --field: #121b23; --accent: #67e8f9; --button: #67e8f9; --error: #fda4af; }
    }
    :root[data-theme="dark"] { color-scheme: dark; --bg: #0b1015; --ink: #eff7fa; --muted: #94a6b2; --line: #2c3942; --field: #121b23; --accent: #67e8f9; --button: #67e8f9; --error: #fda4af; }
    :root[data-theme="light"] { color-scheme: light; }
    * { box-sizing: border-box; }
    body { margin: 0; padding: 24px; background: var(--bg); color: var(--ink); font: 15px/1.5 system-ui, sans-serif; }
    main { max-width: 560px; margin: 0 auto; }
    p { margin: 0; }
    .fields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; }
    label { display: block; font-size: 13px; font-weight: 550; }
    input, select, button { font: inherit; }
    input, select { width: 100%; min-width: 0; margin-top: 7px; min-height: 46px; padding: 11px 10px; border: 1px solid var(--line); border-radius: 7px; background: var(--field); color: var(--ink); }
    :focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
    button { min-height: 46px; margin-top: 14px; padding: 11px 18px; border: 0; border-radius: 7px; background: var(--button); color: #07313c; cursor: pointer; font-size: 14px; font-weight: 650; }
    button:disabled { opacity: .55; cursor: wait; }
    #status { min-height: 44px; margin-top: 14px; color: var(--muted); font-size: 13px; }
    #status[data-error="true"] { color: var(--error); }
    #result { border-top: 1px solid var(--line); padding: 20px 0; }
    .distance { font-size: clamp(30px, 7vw, 46px); font-weight: 550; letter-spacing: -.045em; color: var(--accent); }
    #route, #other-unit { color: var(--muted); font-size: 13px; overflow-wrap: anywhere; }
    #route { margin-bottom: 8px; }
    @media (max-width: 380px) { body { padding: 18px; } .fields { grid-template-columns: 1fr 1fr; } button { width: 100%; } }
  </style>
</head>
<body>
  <main>
    <!-- example:form -->
    <form id="distance-form">
      <div class="fields">
        <label for="from">From ZIP
          <input id="from" name="from" type="text" inputmode="numeric" pattern="[0-9]{5}" maxlength="5"
            title="Enter a five-digit US ZIP code" value="28202" required>
        </label>
        <label for="to">To ZIP
          <input id="to" name="to" type="text" inputmode="numeric" pattern="[0-9]{5}" maxlength="5"
            title="Enter a five-digit US ZIP code" value="10001" required>
        </label>
      </div>
      <button type="submit">Calculate distance</button>
      <p id="status" role="status" aria-live="polite" aria-atomic="true"></p>
    </form>
    <!-- /example:form -->
    <div id="result" hidden>
      <p id="route"></p>
      <p id="distance" class="distance"></p>
      <p id="other-unit"></p>
    </div>
  </main>
  <script>
    // Use a public key restricted to your development and production hostnames.
    const API_KEY = 'YOUR_PUBLIC_API_KEY';
    const form = document.querySelector('#distance-form');
    const from = document.querySelector('#from');
    const to = document.querySelector('#to');
    const button = form.querySelector('button');
    const status = document.querySelector('#status');
    const result = document.querySelector('#result');
    let controller;
    let revision = 0;

    function setStatus(message, error = false) {
      status.textContent = message;
      status.dataset.error = String(error);
    }

    function cancelRequest() {
      revision += 1;
      controller?.abort();
      controller = undefined;
      button.disabled = false;
      form.setAttribute('aria-busy', 'false');
    }

    async function lookupDistance(start, end, signal) {
      if (!API_KEY.startsWith('parse_public_')) {
        throw new Error('Add your public API key and allow this hostname in its domain list.');
      }
      // example:request
      const url = new URL(`https://api.parseapi.com/postal/${encodeURIComponent(start)}/distance/${encodeURIComponent(end)}`);
      url.search = new URLSearchParams({ country: 'US', key: API_KEY });
      const response = await fetch(url, { headers: { 'X-API-Version': '2.1.0' }, signal });
      // /example:request
      if (!response.ok) {
        const messages = {
          400: 'Check both ZIPs. Some ZIPs have no coordinates for a distance calculation.',
          401: 'Check your public API key.',
          403: 'Check your public key, its allowed hostnames, and your account access.',
          404: 'One or both ZIPs were not found in the covered data. Try another pair.',
          429: 'The request limit was reached. Try again later.'
        };
        throw new Error(messages[response.status] || 'The distance lookup is unavailable. Try again shortly.');
      }
      const data = await response.json();
      if (data?.country !== 'US' || data.from?.postal !== start || data.to?.postal !== end) {
        throw new Error('The lookup returned an unexpected ZIP or country. Try again.');
      }
      return data;
    }

    // example:result
    function showDistance(data) {
      if (!data || !data.from || !data.to) {
        throw new Error('The lookup returned an unexpected response. Try again.');
      }
      // Both units are returned. Never coerce a missing value into zero.
      if (!Number.isFinite(data.distance) || data.distance < 0 || !Number.isFinite(data.distance_mi) || data.distance_mi < 0) {
        throw new Error('Distance is unavailable for these ZIPs. Try another pair.');
      }
      if ([data.from, data.to].some(place => !(place.city === null || typeof place.city === 'string'))) {
        throw new Error('The lookup returned an unexpected place label. Try again.');
      }
      const label = (place) => place.city ? `${place.postal} (${place.city})` : place.postal;
      document.querySelector('#route').textContent = `${label(data.from)} to ${label(data.to)}`;
      const formatted = data.distance_mi.toLocaleString('en-US', { maximumFractionDigits: 2 });
      document.querySelector('#distance').textContent = `${formatted} miles`;
      document.querySelector('#other-unit').textContent = `${data.distance.toLocaleString('en-US', { maximumFractionDigits: 2 })} km · approximate straight-line distance`;
      result.hidden = false;
      setStatus(`Distance calculated: ${formatted} miles in a straight line.`);
    }
    // /example:result

    form.addEventListener('input', () => {
      cancelRequest();
      result.hidden = true;
      setStatus('Calculate again to use the changed values.');
    });

    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      if (!form.reportValidity()) return;
      cancelRequest();
      result.hidden = true;
      const current = revision;
      controller = new AbortController();
      const request = controller;
      let timedOut = false;
      const timeout = setTimeout(() => { timedOut = true; request.abort(); }, 10000);
      button.disabled = true;
      form.setAttribute('aria-busy', 'true');
      setStatus('Calculating the distance...');
      try {
        const data = await lookupDistance(from.value, to.value, request.signal);
        if (current !== revision) return;
        if (request.signal.aborted) throw new Error('The lookup was cancelled.');
        showDistance(data);
      } catch (error) {
        if (current !== revision) return;
        const message = timedOut ? 'The lookup timed out. Try again.'
          : error instanceof TypeError ? 'Could not reach ParseAPI. Check your connection and try again.'
          : error instanceof SyntaxError ? 'The response could not be read. Try again.' : error.message;
        setStatus(message, true);
      } finally {
        clearTimeout(timeout);
        if (current === revision) cancelRequest();
      }
    });
  </script>
</body>
</html>
Try the complete example on your computer

Replace YOUR_PUBLIC_API_KEY in the HTML with your public key and add localhost to its allowed domains. Serve the download folder over HTTP:

Terminal · Python 3
python3 -m http.server 8000

Open localhost:8000/zip-code-distance.html. Add your website's hostname to the key when using the feature there.

For every field and parameter, see Postal API reference.

Build something else

All tutorials →