Geoapify Postcode API 教學:用 JavaScript 列出並繪製 3 公里範圍內的 ZIP Code
25 ZIP Codes in One 3 km Circle: List and Draw Them with JavaScript
教學展示如何用 Geoapify Postcode API 及 JavaScript 查詢圓形範圍內的 ZIP Code 區域,並以 Turf 裁切及繪製地圖。以 Boston Common 為例,3 公里範圍查得 25 個區域,其中 12 個完全在圓內,13 個從外圍延伸進入;API 預設 limit 為 5,需提高 limit 才能取回完整結果。
How many ZIP codes are within 3 km of Boston Common? Twenty-five. Around the Alaska State Capitol in Juneau, the same circle holds two.
"Which ZIP codes are within X km?" comes up whenever you plan a delivery zone, a service area, local ads or a sales territory. In this tutorial we answer it with one API request and draw the answer on a map: every ZIP code area in a circle, in its own color, cut to the circle's edge. At the end, we ask an AI coding assistant to build the same page.
TL;DR
- One request to the Postcode API,
/v1/postcode/list?filter=circle:lon,lat,meters, returns every ZIP code area that reaches into the circle, with its shape (geometry=original). - Set
limit. The default is 5, so without it Boston's 25 ZIP codes come back as 5, with no warning. - "Reaches into" is not "inside": in Boston, 12 of the 25 areas lie entirely inside the 3 km circle, and 13 reach in from outside. Turf's
intersectcuts them to the circle. - Cost: 1 credit per 20 postcodes, so Boston's 25 cost 2 credits. The Free plan has 3,000 credits a day.
- An AI assistant found the right endpoint and parameters from a vague prompt, but drew whole ZIP areas reaching far beyond the circle. A precise prompt got our demo.
👉 Live demo: click anywhere in the US to move the circle, or change the radius.
Table of Contents
- Why the first answer is 5
- Within 3 km, or touching the circle?
- How many ZIP codes fit in 3 km?
- Step 1: Request the ZIP codes in a circle
- Step 2: Cut each ZIP area to the circle
- Step 3: Color and label the areas
- Let an AI assistant write it
- Summary
- FAQ
Why the first answer is 5
Here is the most natural first request, a 3 km circle around Boston Common:
https://api.geoapify.com/v1/postcode/list?filter=circle:-71.0656,42.3550,3000&geometry=original&apiKey=YOUR_API_KEY
It returns 5 ZIP codes: 02108, 02109, 02110, 02111 and 02113. That looks plausible for downtown, and nothing in the response says there are more.
The list endpoint returns 5 results by default. Add limit=100 and the same circle gives 25. The maximum is 500, and offset pages through longer lists. The cost is per postcode returned, not per request, so a higher limit only costs more when there really are more ZIP codes.
Within 3 km, or touching the circle?
The circle filter returns every ZIP code area that reaches into the circle, not only those that fit inside. Draw the 25 areas whole, and they spread far past the circle, across Logan Airport, Roxbury and Somerville:
| Boston Common, 3 km | ZIP code areas |
|---|---|
Returned by filter=circle
|
25 |
| Entirely inside the circle | 12 |
| Reach in from outside | 13 |
So "25 ZIP codes within 3 km" needs a footnote: 13 of them are mostly outside. For a delivery zone that's usually what you want (any ZIP you partly serve), but on a map it looks wrong. Cut each area to the circle, and the picture matches the question:
How many ZIP codes fit in 3 km?
It depends a lot on the city. ZIP codes are drawn for mail delivery, so a dense downtown is split into many small ones, and a small city may have one ZIP for everything. The same 3 km circle, same request, in six places:
| Center of the 3 km circle | ZIP code areas | Credits |
|---|---|---|
| Boston Common, MA | 25 | 2 |
| Downtown Los Angeles, CA | 14 | 1 |
| Downtown Nashville, TN | 12 | 1 |
| Downtown Providence, RI | 10 | 1 |
| Nevada State Capitol, Carson City | 3 | 1 |
| Alaska State Capitol, Juneau | 2 | 1 |
In Juneau, ZIP 99801 covers almost the whole circle. Its full area runs far beyond it, which is one more reason to cut the shapes to the circle.
Step 1: Request the ZIP codes in a circle
One GET request with the circle in the filter parameter:
async function getZipCodes(lon, lat, radius) {
const params = new URLSearchParams({
filter: `circle:${lon},${lat},${radius}`, // radius in meters
countrycode: "us",
geometry: "original", // the ZIP code area, not only its point
limit: 100, // the default is 5
apiKey: "YOUR_API_KEY",
});
const response = await fetch(`https://api.geoapify.com/v1/postcode/list?${params}`);
return response.json(); // GeoJSON FeatureCollection
}
| Parameter | Value | What it does |
|---|---|---|
filter |
circle:lon,lat,radius |
Area to search, radius in meters. rect:lon1,lat1,lon2,lat2 and place:<place_id> work too. |
countrycode |
us |
Only US ZIP codes, so a circle near a border stays in one country. |
geometry |
original |
Return each postcode's area. The default is a point. |
limit |
100 |
Maximum results. Default 5, maximum 500. |
offset |
0 |
Skip results, for paging through long lists. |
Each feature has the ZIP code in properties.postcode and its area as a GeoJSON Polygon or MultiPolygon, ready for a map source.
Step 2: Cut each ZIP area to the circle
Build the circle with Turf, then intersect every ZIP area with it. Comparing the areas before and after tells you whether a ZIP lies entirely inside:
const circle = turf.circle([lon, lat], radius / 1000, { units: "kilometers", steps: 128 });
const clipped = zipCodes.features.map((feature, i) => {
const inside = turf.intersect(turf.featureCollection([feature, circle]));
return {
type: "Feature",
geometry: (inside || feature).geometry,
properties: {
postcode: feature.properties.postcode,
color: COLORS[i % COLORS.length], // a small palette, repeated
entirelyInside: inside ? turf.area(inside) / turf.area(feature) > 0.999 : false,
},
};
});
-
turf.circlemakes a polygon in kilometers, so the same shape is drawn on the map and used for cutting. -
turf.intersectreturns only the part of the ZIP area inside the circle. - The color goes into each feature, so one map layer can draw all of them.
Step 3: Color and label the areas
Two layers on one GeoJSON source: a fill colored from each feature's color, and a label with the ZIP code.
map.addSource("zip-areas", { type: "geojson", data: turf.featureCollection(clipped) });
map.addLayer({
id: "zip-areas-fill",
type: "fill",
source: "zip-areas",
paint: { "fill-color": ["get", "color"], "fill-opacity": 0.45 },
});
map.addLayer({
id: "zip-labels",
type: "symbol",
source: "zip-areas",
layout: { "text-field": ["get", "postcode"], "text-font": ["Noto Sans Bold"], "text-size": 12 },
paint: { "text-color": "#1f2933", "text-halo-color": "#ffffff", "text-halo-width": 1.5 },
});
MapLibre places each label inside its polygon. A ZIP made of several parts (a MultiPolygon) gets a label in each part. Noto Sans Bold is one of the fonts in the Geoapify OSM Bright map style.
In the demo, a map click moves the circle and runs the request again, and a response that arrives after a newer click is ignored. The whole demo is 154 lines of JavaScript, including the panel with the counts and the ZIP list.
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 that shows all ZIP codes within 3 km of Boston Common on a map. One HTML file please.
The API part was right, which surprised us: /v1/postcode/list with filter=circle, geometry=original and limit=100. It found the same 25 ZIP codes, in 87 lines with Leaflet.
The map is where it fell short. It drew the whole ZIP areas in one color, so they spread almost twice as wide as the circle, and the small downtown ZIPs are hard to tell apart. The box says "25 ZIP codes within 3 km", although 13 of them are mostly outside. Nothing in the prompt said what "within" should mean, so the assistant took the API's answer as it was.
Prompt 2, precise: we named the libraries and versions, the endpoint with all four parameters, the cutting step with turf.intersect, a color per area, the labels, and the panel.
The same result as our demo: 25 ZIP areas, 12 entirely inside, cut to the circle, in 180 lines (HTML, CSS and JavaScript in one file). It also handled empty intersections and outdated responses.
What made the difference:
- Say what "within" means. The API returns every ZIP that touches the circle. Whether you draw whole areas, cut them, or count only those entirely inside is your decision, so put it in the prompt.
-
The parameters were right in both runs. Even the vague prompt got
limitandgeometry=original. Still, name them: a missinglimitfails silently at 5. - Ask for a color per area. One color for 25 neighbouring shapes is hard to read.
- Name the versions. Otherwise you get the libraries the assistant remembers.
Summary
-
GET /v1/postcode/list?filter=circle:lon,lat,meters&geometry=original&limit=100lists every ZIP code area that reaches into a circle, with its shape. - Always set
limit: the default of 5 cuts the list without a warning. The maximum is 500, andoffsetpages further. - The circle filter includes ZIP areas that only touch the circle. Cut them with
turf.intersectto draw them, or compare areas to count only those entirely inside. -
filter=rect:lists the ZIP codes in a rectangle, for example the visible map. - Cost: 1 credit per 20 postcodes in the response.
FAQ
How do I find all ZIP codes within a radius?
Send GET https://api.geoapify.com/v1/postcode/list?filter=circle:lon,lat,radiusMeters&countrycode=us&limit=100&apiKey=…. The response lists every ZIP code area that reaches into the circle. Add geometry=original to get the areas for a map.
Why do I only get 5 ZIP codes?
limit defaults to 5. Set it higher, up to 500, and use offset for more.
Does the circle filter return ZIP codes that are only partly inside?
Yes. Around Boston Common, 13 of the 25 ZIP areas returned for a 3 km circle reach in from outside. Use turf.intersect to cut them to the circle, or compare turf.area before and after to keep only those entirely inside.
How many credits does a ZIP code list cost?
1 credit per 20 postcodes in the response, so 25 ZIP codes cost 2 credits and 100 cost 5. The Free plan includes 3,000 credits a day.
Can I get the ZIP codes in the visible map area instead of a circle?
Yes: filter=rect:west,south,east,north with the map bounds, for example from MapLibre's map.getBounds().
Are ZIP code areas official boundaries?
Not exactly. ZIP codes are mail delivery routes, and USPS doesn't publish them as areas. Every ZIP code map, including this one, shows approximate areas. Some ZIP codes, for example PO-box-only ones, have no area of their own.
Does it work outside the US?
The Postcode API lists postcodes in many countries, with their shapes where the data has them. In some countries, such as the UK, full postcodes come back as points, so draw them as markers instead of areas.
Try it
- 👉 Live demo on CodePen
- 📦 Source code on GitHub: three files, no build step
- 📖 Postcode API documentation
More ZIP and address tutorials:
- The ZIP Already Knows the City: Autofill City and State, Then Check the Address
- A 5-Mile Radius Isn't 5 Miles by Car: Draw Both on a Map with JavaScript
Get a free API key at myprojects.geoapify.com and try the circle on your own city. How many ZIP codes are within 3 km of your office? Tell us in the comments.
來源:DEV Community · dev.to





