DEV Community

Cover image for 3.6 km Apart, 7.8 km by Car: Distance Between Two Postal Codes in JavaScript
Casey Rivers for Geoapify Maps API

Posted on

3.6 km Apart, 7.8 km by Car: Distance Between Two Postal Codes in JavaScript

ZIP codes 10004 (Lower Manhattan) and 07302 (Jersey City) are 3.6 km apart as the crow flies. By car, it's 7.8 km and 12 minutes, because the Hudson River is in the way and the road goes through the Holland Tunnel.

"How far is postal code A from postal code B?" comes up in shipping quotes, delivery zones, service areas and "find the nearest branch" forms. In this tutorial we answer it twice, as a straight line and as a driving route, and draw both on a map. At the end, we ask an AI coding assistant to build the same page.

TL;DR

  • A postal code is an area. To measure a distance, first turn each code into a point with the Geocoding API: postcode=10001&type=postcode&filter=countrycode:us.
  • Always pass the country. Without it, 10001 first matches postcodes in Algeria, Spain and Estonia, and an AI-written page happily measured 132.5 km between two towns in Algeria.
  • The straight-line distance needs no API: the haversine formula, ten lines of JavaScript.
  • The driving distance and time come from the Routing API: one GET with two waypoints, distance in meters, time in seconds.
  • The road is 1.14 to 2.19 times longer than the straight line in our examples: Berlin β†’ Hamburg Γ— 1.14, across the Hudson Γ— 2.19.
  • One calculation costs 3 credits (two geocoding requests and one route under 500 km). The Free plan has 3,000 credits a day.

πŸ‘‰ Live demo: pick a country or type your own postal codes.


Table of Contents

  1. Why the straight line isn't the answer
  2. How much longer is the road?
  3. Postal code 10001: which one?
  4. Step 1: Turn each postal code into a point
  5. Step 2: The straight-line distance
  6. Step 3: The driving distance and time
  7. Step 4: Draw both on the map
  8. Let an AI assistant write it
  9. Summary
  10. FAQ

Why the straight line isn't the answer

The straight-line ("great-circle") distance is easy to calculate and good for a first filter. But nobody drives in a straight line: rivers, bays, mountains and the road network decide how far a trip really is.

Map of Lower Manhattan and Jersey City. A dashed straight line of 3.6 km runs across the Hudson River from ZIP 10004 to ZIP 07302; the blue driving route of 7.8 km and 12 minutes goes north along the West Side Highway and through the Holland Tunnel

From Lower Manhattan, the car goes north along the West Side Highway to the Holland Tunnel, crosses under the river and comes back south in Jersey City: 7.8 km by road for 3.6 km in a straight line.

How much longer is the road?

We measured a few postal code pairs both ways. The ratio "road Γ· straight line" shows how much the straight line underestimates the trip.

Four maps, each with a dashed straight line and a blue driving route between two postal codes: San Francisco 94103 to Alameda 94501, 13.8 km straight and 24.5 km by road, ratio 1.78; Manhattan 10001 to Staten Island 10301, 15.7 and 27.3 km, ratio 1.74; Boulder 80302 to Breckenridge 80424 through the mountains, 88.2 and 138.2 km, ratio 1.57; Berlin 10115 to Hamburg 20095, 253.0 and 289.6 km, ratio 1.14

From β†’ To Straight line By road Drive time Road Γ· straight
10004 Lower Manhattan β†’ 07302 Jersey City 3.6 km 7.8 km 12 min Γ— 2.19
94103 San Francisco β†’ 94501 Alameda 13.8 km 24.5 km 22 min Γ— 1.78
10001 Manhattan β†’ 10301 Staten Island 15.7 km 27.3 km 30 min Γ— 1.74
80302 Boulder β†’ 80424 Breckenridge 88.2 km 138.2 km 1 h 43 min Γ— 1.57
02108 Boston β†’ 02138 Cambridge 6.4 km 8.8 km 10 min Γ— 1.38
SW1A 1AA London β†’ M1 1AE Manchester 261.9 km 321.7 km 3 h 15 min Γ— 1.23
110001 New Delhi β†’ 560001 Bengaluru 1,740.6 km 2,093.6 km 26 h 41 min Γ— 1.20
10001 New York β†’ 19107 Philadelphia 132.6 km 154.1 km 1 h 44 min Γ— 1.16
10115 Berlin β†’ 20095 Hamburg 253.0 km 289.6 km 2 h 55 min Γ— 1.14

Routing API, mode=drive, default traffic=free_flow (no traffic jams). Each postal code is the point the Geocoding API returns for it.

Long trips on highways stay around Γ— 1.15 to 1.25. Short trips across water or through mountains can be twice as long as the straight line. If a price or a promise depends on the distance, use the road.

Postal code 10001: which one?

Postal codes aren't unique worldwide. Many countries use five-digit codes, so the same number exists in several of them.

World map with the first three Geocoding API results for postal code 10001 without a country filter, all in red: 1. Bouira, Algeria; 2. CΓ‘ceres, Spain; 3. Tallinn, Estonia. A green marker in New York shows the result with filter=countrycode:us

Request First result
postcode=10001 10001 Bouira, Algeria
postcode=10001&filter=countrycode:us Manhattan, New York, NY 10001
postcode=10115 Santo Domingo, Dominican Republic
postcode=10115&filter=countrycode:de Mitte, 10115 Berlin

The answer without a filter isn't wrong: those postcodes exist. It just isn't the one you meant. Ask for the country in your form, or take it from your users' shipping country.

Step 1: Turn each postal code into a point

A structured Geocoding API request with only postcode set finds the postal code itself, not a street or an address in it.

async function geocodePostcode(postcode, country) {
  const params = new URLSearchParams({
    postcode,                         // structured input: the postal code alone
    type: "postcode",                 // a postal code result, not an address in it
    filter: `countrycode:${country}`, // "us", "in", "gb", "de", ...
    limit: 1,
    format: "json",
    apiKey: "YOUR_API_KEY",
  });
  const response = await fetch(`https://api.geoapify.com/v1/geocode/search?${params}`);
  const data = await response.json();
  return data.results[0]; // { lat, lon, formatted, city, ... } or undefined
}

const [from, to] = await Promise.all([
  geocodePostcode("10001", "us"),
  geocodePostcode("19107", "us"),
]);
Enter fullscreen mode Exit fullscreen mode
Parameter Value Why
postcode 10001, SW1A 1AA, 110001 Structured input; don't combine it with text
type postcode Return the postal code, not an address that has it
filter countrycode:us Keep the search in one country
limit 1 We only need the best match
format json A plain results array instead of GeoJSON

An empty results array means the code wasn't found: show a message instead of a distance. Each request costs 1 credit.

Step 2: The straight-line distance

The straight-line distance needs no request. The haversine formula gives the great-circle distance between two points on a sphere.

function haversineDistance(a, b) {
  const R = 6371008.8; // mean Earth radius in meters
  const toRad = (deg) => (deg * Math.PI) / 180;
  const dLat = toRad(b.lat - a.lat);
  const dLon = toRad(b.lon - a.lon);
  const h = Math.sin(dLat / 2) ** 2 +
    Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.sin(dLon / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(h)); // meters
}

const straightLine = haversineDistance(from, to); // β‰ˆ 132,600 m for 10001 β†’ 19107
Enter fullscreen mode Exit fullscreen mode

Divide by 1,000 for kilometers or by 1,609.344 for miles. The sphere is an approximation; for distances like these, the error is well under 1%.

Step 3: The driving distance and time

The Routing API takes the two points as waypoints and returns the route as GeoJSON, with its length and duration.

async function getRoute(from, to) {
  const params = new URLSearchParams({
    waypoints: `${from.lat},${from.lon}|${to.lat},${to.lon}`, // lat,lon β€” latitude first
    mode: "drive",
    apiKey: "YOUR_API_KEY",
  });
  const response = await fetch(`https://api.geoapify.com/v1/routing?${params}`);
  return response.json(); // GeoJSON FeatureCollection
}

const route = await getRoute(from, to);
const { distance, time } = route.features[0].properties; // meters, seconds
Enter fullscreen mode Exit fullscreen mode
Parameter Value Why
waypoints `lat,lon\ lat,lon`
mode drive Car; also truck, bicycle, walk and more
units metric (default) or imperial imperial returns the distance in miles
traffic free_flow (default) or approximated approximated slows down roads that are usually busy

A route costs 1 credit per waypoint pair, plus 1 credit for each full 500 km. So 10001 β†’ 19107 (154 km) costs 1 credit, and New Delhi β†’ Bengaluru (2,094 km) costs 5.

Step 4: Draw both on the map

The route is GeoJSON, so it goes straight into a MapLibre source. The straight line is a two-point LineString, drawn dashed.

map.addSource("route", { type: "geojson", data: route.features[0] });
map.addLayer({
  id: "route-line",
  type: "line",
  source: "route",
  layout: { "line-join": "round", "line-cap": "round" },
  paint: { "line-color": "#4263eb", "line-width": 5 },
});

map.addSource("straight-line", {
  type: "geojson",
  data: {
    type: "Feature",
    geometry: { type: "LineString", coordinates: [[from.lon, from.lat], [to.lon, to.lat]] },
  },
});
map.addLayer({
  id: "straight-line",
  type: "line",
  source: "straight-line",
  paint: { "line-color": "#1f2933", "line-width": 2, "line-dasharray": [3, 2] },
});

new maplibregl.Marker({ color: "#2f9e44" }).setLngLat([from.lon, from.lat]).addTo(map);
new maplibregl.Marker({ color: "#e03131" }).setLngLat([to.lon, to.lat]).addTo(map);
Enter fullscreen mode Exit fullscreen mode

The demo page with Germany selected: a panel with the postal codes 10115 and 20095 and the results 253.0 km straight line, 289.6 km driving distance, 2 h 55 min driving time and road to straight line ratio 1.14; the map shows the dashed straight line and the blue route from Berlin to Hamburg

Note the coordinate order: the Routing API waypoints take lat,lon, while GeoJSON and MapLibre use [lon, lat]. Mixing them up is the most common bug in this kind of page.

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:

Using the Geoapify API, make a web page where I enter two postal codes and it shows the distance between them. One HTML file please.

Page written by an AI assistant from the vague prompt: two postal code fields with 10001 and 19107, two empty optional country fields, and the result 132.5 km straight-line distance and 159.8 km by car (1 h 31 min); the addresses below read "10001 Bouira, Algeria" and "19107 AΓ―n Arnat, Algeria"

A clean page in 109 lines: geocoding, haversine and the Routing API, all called correctly. It even added an optional country field per postal code.

But we typed 10001 and 19107, the way a user would, and left the optional field empty. The page said 132.5 km straight and 159.8 km by car. That looks right (the real New York β†’ Philadelphia distance is 132.6 km), but both points were in Algeria: Bouira and AΓ―n Arnat. Only the small address lines below the result give it away. With us typed into both country fields, the same page returned the correct 132.6 km and 154.1 km.

Two smaller points: it searched with free text (text=10001) instead of the structured postcode parameter, and it has no map, so there's nothing to show which 10001 it found.

Prompt 2, precise: we named the library and version, the structured geocoding request with type=postcode and the country filter, the haversine calculation, the Routing API request and the fields to read, what to draw on the map, the result rows, and the "not found" message.

Page written by an AI assistant from the precise prompt: a panel with a country select set to United States, the postal codes 10001 and 19107, and the results 132.6 km / 82.4 mi straight line, 154.1 km / 95.7 mi driving distance, 1 h 44 min, ratio 1.16; the map shows green and red markers, a dashed straight line and the blue route from New York to Philadelphia

The same result as our demo in 202 lines: 132.6 km straight, 154.1 km and 1 h 44 min by road. We also tested the country switch (London β†’ Manchester: 261.9 km and 321.7 km, Γ— 1.23) and a code that doesn't exist (00000 β†’ "Postal code not found: 00000"). Both worked.

What made the difference:

  • Make the country required. An optional country field means most users won't fill it in, and the result is plausible but wrong.
  • Ask for the structured postcode parameter with type=postcode, so the search looks for postal codes only.
  • Ask for a map, or at least show the matched place next to the number. A distance alone hides a wrong match.
  • Say which fields to read: distance in meters, time in seconds.

Summary

  • Postal code β†’ point: Geocoding API with postcode, type=postcode and filter=countrycode:xx. Never without the country.
  • Straight line: haversine in JavaScript, no request. Good for a quick filter or a "within X km" check.
  • By road: Routing API with two waypoints (lat,lon), mode=drive. Use it whenever a price, a delivery promise or a travel time depends on the distance.
  • Expect the gap: the road is 1.14 to 2.19 times longer in our examples; water and mountains make it larger.
  • Many pairs at once: for one origin and many destinations, the Route Matrix API returns all distances and times in one request.
  • Cost: 1 credit per geocoded postal code, 1 credit per route (+1 per full 500 km).

FAQ

How do I calculate the distance between two ZIP codes in JavaScript?
Geocode each ZIP code with https://api.geoapify.com/v1/geocode/search?postcode=10001&type=postcode&filter=countrycode:us&format=json, then calculate the haversine distance between the two lat/lon points. For the distance by road, send both points to the Routing API.

Does it work for India PIN codes, UK postcodes and other countries?
Yes. Pass the code and the country: postcode=110001&filter=countrycode:in or postcode=SW1A 1AA&filter=countrycode:gb. The demo includes the US, India, the UK and Germany.

Which point of the postal code is used?
The point the Geocoding API returns for the postal code area. A postal code can cover a few blocks or hundreds of square kilometers, so for exact door-to-door distances, geocode the full addresses instead.

Why is the driving distance so much longer than the straight line?
Roads go around water, through mountain valleys and along the street grid. In our examples the road is 14% to 119% longer; crossing the Hudson from Lower Manhattan to Jersey City is the extreme case.

How do I get miles instead of kilometers?
Divide meters by 1,609.344, or add units=imperial to the Routing API request to get the route distance in miles.

What does one calculation cost?
Two geocoding requests (1 credit each) and one route (1 credit, plus 1 for each full 500 km): usually 3 credits. The Free plan includes 3,000 credits a day.

Does the drive time include traffic?
By default no: traffic=free_flow assumes empty roads. traffic=approximated slows down roads that are usually busy. Neither is live traffic.


Try it

Related quickstart samples:

More distance tutorials:

Get a free API key at myprojects.geoapify.com and try your own postal codes. Which pair of postal codes near you has the biggest gap between the straight line and the road? Tell us in the comments.

Top comments (0)