How to Calculate the Driving Distance Between Two Postal Codes (ZIP or PIN)
- API or service
- Geocoding API + Routing API
- Task
- Two postal codes → center points → straight-line and driving distance
- Examples
- Difficulty
- Beginner
- Time
- 10 min
Calculate the distance between two postal codes
You have two postal codes, such as US ZIP codes or Indian PIN codes, and need the distance between them: as the crow flies, by road, or both. Typical uses are delivery fees by distance, service-area checks, shipping estimates, and "how far is it" calculators where users type only a postal code.
A postal code is an area, not a point. Get a representative point for each code with the Geoapify Forward Geocoding API, then measure the straight line between the two points and request the driving route between them with the Geoapify Routing API.
Task flow: two postal codes + country → Geocoding API (type=postcode) → two center points → straight-line distance (haversine) and Routing API driving distance and time.
| Example | Straight line | Driving distance | Driving time |
|---|---|---|---|
| ZIP 94103 San Francisco → ZIP 94612 Oakland, US | 8.2 mi | 9.9 mi | 15 min |
| PIN 560001 Bengaluru → PIN 600001 Chennai, India | 290.1 km | 356.8 km | 4 h 24 min |
In both examples, the road is 22–23% longer than the straight line: the San Francisco route crosses the bay on the Bay Bridge, north of the straight line.
From postal codes to distances
Three requests answer the question for one pair of postal codes:
| Step | Service | Input | Output |
|---|---|---|---|
| 1 | Geocoding API | First postal code + country | Center point (lat, lon) of the postal code |
| 2 | Geocoding API | Second postal code + country | Center point of the second postal code |
| 3 | Your code | Two center points | Straight-line distance (haversine formula) |
| 4 | Routing API | Two center points as waypoints | Driving distance and time |
Each geocoding request returns one result and costs 1 credit. A route with two waypoints costs 1 credit, plus 1 credit for every full 500 km of route distance. Both examples in this guide cost 3 credits per pair.
Always send the country
The same digits are used as postal codes in several countries. Without a country filter, postcode=600001 returns Bacău, Romania, as the first result, before Chennai, India. postcode=94103 also matches postal codes in Lithuania, Poland, and Slovakia. Send the country with every request:
| Country | Postal code format | Example | Filter |
|---|---|---|---|
| United States | 5-digit ZIP code | 94103 |
filter=countrycode:us |
| India | 6-digit PIN code | 560001 |
filter=countrycode:in |
What the distance means
A postal code covers an area, and the API returns one point inside or near that area. Both distances are measured between these points, so they describe the distance between the two postal code areas in general, not between two specific addresses. When you have full addresses, geocode the addresses instead: see How to Convert an Address to Coordinates.
- Straight-line distance is the shortest distance over the Earth's surface. Use it for radius checks, such as "within 10 miles", and when no road distance is needed. It costs no API request.
- Driving distance follows roads open to cars and comes with a travel time. Use it for delivery fees, travel estimates, and anything a driver pays for. It is never shorter than the straight line.
The Postcode Search API can replace the Geocoding API in steps 1 and 2; see Get the center point of each postal code.
Get the center point of each postal code
Send the postal code in the structured postcode parameter, set type=postcode so that only postal code results are returned, and restrict the search to one country with filter=countrycode:<code>. limit=1 returns only the best match.
https://api.geoapify.com/v1/geocode/search?postcode=94103&type=postcode&filter=countrycode:us&format=json&limit=1&apiKey=YOUR_API_KEY
| Parameter | Value | Meaning |
|---|---|---|
postcode |
94103 |
The postal code to find. |
type |
postcode |
Return postal codes only, not streets or places with the same number. |
filter |
countrycode:us |
Search in the United States only. Use countrycode:in for Indian PIN codes. |
format |
json |
Return a results array instead of GeoJSON. |
limit |
1 |
Return the best match only. |
Reduced response: The full result also contains datasource, timezone, other_names, plus_code, place_id, and bbox.
{
"results": [
{
"country": "United States",
"country_code": "us",
"state": "California",
"city": "San Francisco",
"postcode": "94103",
"state_code": "CA",
"result_type": "postcode",
"lon": -122.411302285,
"lat": 37.774494791,
"formatted": "San Francisco, CA 94103, United States of America",
"rank": {
"confidence": 1,
"match_type": "full_match"
}
}
]
}
Use lat and lon as the point of the postal code. Before you use them, check that a result exists, that result_type is postcode, and that postcode is the code you sent. An empty results array means that the code was not found in that country.
Request the second postal code the same way. These are the center points used in the rest of this guide:
| Postal code | Country | lat |
lon |
formatted |
|---|---|---|---|---|
| 94103 | us |
37.774494791 | -122.411302285 | San Francisco, CA 94103, United States of America |
| 94612 | us |
37.808353396 | -122.268286768 | Oakland, CA 94612, United States of America |
| 560001 | in |
12.979703737 | 77.594694984 | Bengaluru - 560001, KA, India |
| 600001 | in |
13.083243217 | 80.270567051 | Zone 5 Royapuram, Chennai - 600001, TN, India |
Alternative: Postcode Search API
The Postcode Search API looks up postal codes only, so it needs no type parameter. Send the country as countrycode:
https://api.geoapify.com/v1/postcode/search?postcode=94103&countrycode=us&format=json&apiKey=YOUR_API_KEY
It returns the same kind of result, with lat and lon of the postal code. For ZIP 94103, the point is 37.7729833, -122.411343, about 170 m from the Geocoding API point; the two APIs can return slightly different points for the same postal code. With geometry=original and the default GeoJSON format, the result also contains the postal code area as a polygon, for example, to draw it on a map. Use one of the two APIs consistently for all postal codes you compare.
For more postal code lookups, such as prefix search, see Geocode ZIP codes. To geocode many postal codes at once, use the Batch Geocoding API with type=postcode and a country filter.
Request the driving distance
Send the two center points to the Routing API as waypoints, in latitude,longitude order and separated by |. Set mode=drive for a car route.
https://api.geoapify.com/v1/routing?waypoints=37.774494791,-122.411302285|37.808353396,-122.268286768&mode=drive&units=imperial&apiKey=YOUR_API_KEY
| Parameter | Value | Meaning |
|---|---|---|
waypoints |
ZIP 94103 center, then ZIP 94612 center | Each point as latitude,longitude; points separated by |. |
mode |
drive |
Route on roads open to passenger cars. |
units |
imperial |
Return the distance in miles. The default, metric, returns meters. |
Reduced response: The route geometry and the turn-by-turn steps are omitted.
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"mode": "drive",
"waypoints": [
{ "location": [-122.411302, 37.774494], "original_index": 0 },
{ "location": [-122.268286, 37.808353], "original_index": 1 }
],
"units": "imperial",
"distance": 9.914,
"distance_units": "miles",
"time": 926.968,
"legs": [{ "distance": 9.914, "time": 926.968 }]
},
"geometry": {
"type": "MultiLineString"
}
}
]
}
distance is the driving distance in distance_units, and time is the travel time in seconds: 9.9 miles and 926.968 / 60 ≈ 15 minutes. The response is GeoJSON, so the geometry can be drawn on a map directly. waypoints[].location repeats the points you sent in [longitude, latitude] order, like all GeoJSON coordinates.
PIN codes in India
The same request with the Bengaluru and Chennai center points and the default metric units:
https://api.geoapify.com/v1/routing?waypoints=12.979703737,77.594694984|13.083243217,80.270567051&mode=drive&apiKey=YOUR_API_KEY
Reduced response: only properties of the route feature.
{
"mode": "drive",
"units": "metric",
"distance": 356828,
"distance_units": "meters",
"time": 15828.978,
"toll": true
}
The drive is 356.8 km and takes about 4 hours 24 minutes. "toll": true means that the route uses toll roads; add avoid=tolls to request a route without them, see How to Avoid Tolls, Highways, and Ferries.
The center of a postal code does not always lie on a road, for example when it falls in a park or on water. The route then starts or ends on a nearby road; the first and last coordinates of the route geometry show where. See How to Handle Unreachable Waypoints to detect points that moved far.
Show both postal codes and the straight-line distance
Use this after creating a MapLibre GL map, with an element <div id="summary"> over it, and waiting for the map's load event. The code geocodes both ZIP codes, calculates the straight-line distance with the haversine formula, and draws the two center points and a dashed straight line between them.
const apiKey = "YOUR_API_KEY";
// Postal code → its center point. Always restrict the search to one country.
async function geocodePostalCode(postcode, countryCode) {
const params = new URLSearchParams({
postcode,
type: "postcode",
filter: `countrycode:${countryCode}`,
format: "json",
limit: 1,
apiKey
});
const response = await fetch(`https://api.geoapify.com/v1/geocode/search?${params}`);
if (!response.ok) throw new Error(`Geocoding request failed: ${response.status}`);
const result = (await response.json()).results?.[0];
if (!result || result.result_type !== "postcode" || result.postcode !== postcode) {
throw new Error(`Postal code ${postcode} was not found in ${countryCode.toUpperCase()}`);
}
return result;
}
// Straight-line (great-circle) distance in meters, haversine formula.
function straightLineMeters(a, b) {
const R = 6371008.8; // mean Earth radius in meters
const rad = degrees => (degrees * Math.PI) / 180;
const dLat = rad(b.lat - a.lat);
const dLon = rad(b.lon - a.lon);
const h = Math.sin(dLat / 2) ** 2 +
Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(h));
}
const from = await geocodePostalCode("94103", "us");
const to = await geocodePostalCode("94612", "us");
const straightMiles = straightLineMeters(from, to) / 1609.344;
// The two postal code centers and the straight line between them.
[from, to].forEach(place => {
const label = document.createElement("div");
label.className = "postcode-label";
label.textContent = `${place.postcode} ${place.city}`;
new maplibregl.Marker({ element: label, anchor: "bottom" })
.setLngLat([place.lon, place.lat])
.addTo(map);
});
map.addSource("straight-line", {
type: "geojson",
data: {
type: "Feature",
properties: {},
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": "#f76707", "line-width": 3, "line-dasharray": [2, 2] }
});
document.querySelector("#summary").textContent =
`Straight line: ${straightMiles.toFixed(1)} mi`;
map.fitBounds([[from.lon, from.lat], [to.lon, to.lat]], { padding: 120, duration: 0 });
The labels and the summary box are styled with this CSS:
/* MapLibre positions the marker element absolutely; do not override `position`. */
.postcode-label {
margin-bottom: 7px;
padding: 4px 8px;
border-radius: 4px;
background: #222222;
color: #ffffff;
font: 600 13px/1.2 sans-serif;
white-space: nowrap;
}
.postcode-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -6px;
margin-left: -6px;
border-width: 6px 6px 0;
border-style: solid;
border-color: #222222 transparent transparent;
}
#summary {
position: absolute;
top: 12px;
left: 12px;
padding: 8px 12px;
border-radius: 6px;
background: #ffffff;
font: 600 15px/1.3 sans-serif;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
}

The screenshot was rendered from this code with MapLibre GL JS 4.7.1 and the Geoapify osm-bright map style.
The haversine formula treats the Earth as a sphere with a mean radius of 6,371,008.8 m. It differs from an ellipsoid calculation by at most about 0.5%, less than the uncertainty of using one point for a whole postal code area. Divide the meters by 1,609.344 for miles or by 1,000 for kilometers.
The straight line crosses San Francisco Bay, where no road runs. The next step adds the road route.
Add the driving route and compare the distances
Run this after the previous step. It uses from, to, straightMiles, and apiKey from there, requests the driving route between the two center points, draws it below the straight line, and shows both distances in the summary box.
const routeParams = new URLSearchParams({
waypoints: `${from.lat},${from.lon}|${to.lat},${to.lon}`, // latitude,longitude|latitude,longitude
mode: "drive",
units: "imperial",
apiKey
});
const routeResponse = await fetch(`https://api.geoapify.com/v1/routing?${routeParams}`);
if (!routeResponse.ok) throw new Error(`Routing request failed: ${routeResponse.status}`);
const route = await routeResponse.json(); // GeoJSON FeatureCollection
const { distance, time } = route.features[0].properties; // miles, seconds
// The road route goes below the straight line.
map.addSource("route", { type: "geojson", data: route });
map.addLayer({
id: "route",
type: "line",
source: "route",
layout: { "line-join": "round", "line-cap": "round" },
paint: { "line-color": "#623aff", "line-width": 5, "line-opacity": 0.8 }
}, "straight-line");
document.querySelector("#summary").textContent =
`Straight line: ${straightMiles.toFixed(1)} mi · Driving: ${distance.toFixed(1)} mi, ${Math.round(time / 60)} min`;
// Fit the map to the whole route, not only to the two centers.
const bounds = new maplibregl.LngLatBounds();
route.features[0].geometry.coordinates.flat().forEach(position => bounds.extend(position));
map.fitBounds(bounds, { padding: 80, duration: 0 });

The screenshot was rendered from this code with MapLibre GL JS 4.7.1 and the Geoapify osm-bright map style.
The Routing API returns the driving distance in miles because of units: "imperial"; the straight-line distance is calculated in the browser. The route is 9.9 miles, 1.8 miles (22%) longer than the straight line, because it has to go north to the Bay Bridge.
URLSearchParams encodes , and | in waypoints as %2C and %7C; the Routing API accepts both forms. For Indian PIN codes, call geocodePostalCode("560001", "in"), omit units to get meters, and divide distance by 1,000 for kilometers.
Postal code distance with an AI coding agent
Copy this prompt into Codex, Claude Code, Cursor, or another coding agent to add a distance calculator for two postal codes to your project.
Add a postal code distance calculator to my project with the Geoapify Geocoding API and Routing API.
Before you start
- Inspect the existing project first. Reuse its current framework, components, styling, HTTP client, map library, and conventions. Make the smallest necessary changes.
- Ask only what the project does not answer: which countries the postal codes come from, whether users need the straight-line distance, the driving distance, or both, miles or kilometers, and whether browser requests use a restricted API key or a backend proxy.
- Read the Geoapify API key from the project's environment configuration. Never hardcode, print, or log it.
Postal code → point
- GET https://api.geoapify.com/v1/geocode/search with postcode=<code>, type=postcode, filter=countrycode:<iso2>, format=json, limit=1.
- Always send the country: the same digits are postal codes in several countries.
- Use results[0].lat and results[0].lon. Treat an empty results array, a result_type other than "postcode", or a postcode that differs from the input as "postal code not found" and show that to the user.
- Normalize the input first: trim spaces; keep leading zeros (ZIP 02108 is a string, not a number).
Distances
- Straight line: haversine formula between the two points, Earth radius 6371008.8 m.
- Driving: GET https://api.geoapify.com/v1/routing with waypoints=<lat>,<lon>|<lat>,<lon> (latitude first), mode=drive, and units=imperial for miles or the default metric for meters.
- Read features[0].properties.distance (in distance_units) and features[0].properties.time (seconds). Show the time in minutes or hours and minutes.
- If a map is used, draw the route geometry (GeoJSON MultiLineString, [longitude, latitude]) and mark both postal code points.
Errors and limits
- Each postal code lookup costs 1 credit; a two-point route costs 1 credit plus 1 per full 500 km.
- Cache postal code points: they do not change between requests.
- Show the API message for HTTP 400 responses, show loading and empty states, and retry 429 responses a limited number of times with backoff.
- Add a test with mocked responses for a found pair, a postal code that is not found, and a routing error.
Review the generated code against the requests in this guide. Check that every lookup sends the country filter, that ZIP codes keep leading zeros, the waypoint order (latitude,longitude), the units of distance, and the API-key handling.