A geocoding API looks trivial: send text, get coordinates. In practice, the bugs that reach production are rarely the geocoder's fault. Coordinates get swapped. The first result is trusted blindly. A box is read in the wrong order. A loop hammers a free service until it blocks you. Results get stored with no record of where they came from. This guide goes through the decisions that prevent those mistakes. The examples call the OpenGeocoder API, but the same principles apply to any provider.
Anatomy of a request
A forward-geocoding request has one essential parameter, the query, and a few that make results far better:
GET https://opengeocoder.net/api/v1/geocode
?q=Sheikh Zayed Road, Dubai
&countrycodes=ae
&limit=5
&lang=en
- Country filter. If you know the country, say so. It removes a whole class of wrong answers, like the Paris in Texas or the Victoria in five countries. It costs nothing.
- A limit above 1. Ask for several candidates even if you plan to use one. You can't tell whether the top answer is uncertain unless you can see what it beat.
- Language. Place names come back in the language you request where the data has it, which matters for display. It doesn't change which places match.
- A viewbox (
west,south,east,north) biases results toward an area, such as your delivery region or the visible map. Addbounded=1to exclude everything outside it.
URL-encode the query. Commas and spaces are fine when encoded, but an unencoded & in “Marks & Spencer” will silently cut your query short.
Reading the candidates
A geocoder returns candidates, not facts. Before using the first one, look at three things.
- What kind of thing matched. In our API,
addresstypeandtypetell you whether you got a house, a road, a suburb or a whole city. If someone typed a full street address and the best match is acity, the geocoder couldn't find the street. The coordinates are the city's centre, which can be many kilometres from the customer. - How specific it is.
place_rankruns from low numbers for continents and countries up to 30 for individual houses. Choose a minimum rank for each use case. A delivery app might reject anything coarser than a street, while a weather widget is happy with a city. - How clear the winner is. If the top two candidates have similar
importanceand are far apart, the query is ambiguous. Show both and let a person choose. The place name search tool does exactly this.
Coordinates and boxes: the ordering trap
Latitude-then-longitude and longitude-then-latitude are both common. Neither is wrong, but mixing them is. Our API sidesteps the problem for points by returning named lat and lon fields. Boxes are harder, because each ecosystem orders them differently:
| Where | Box order |
|---|---|
| GeoJSON (RFC 7946), OpenGeocoder API | [west, south, east, north] |
Nominatim boundingbox | [south, north, west, east] (as strings) |
Leaflet fitBounds | [[south, west], [north, east]] |
| WKT polygon | x y pairs, i.e. lon lat |
Convert at the boundary of your code, in one function, with a test. A quick sanity check is that in a correctly ordered box, south is less than north. The bounding box explorer shows one box in every format side by side, and bounding boxes explained covers the antimeridian case, where west is greater than east.
Rate limits and caching
Free geocoders exist because their operators keep usage reasonable. OpenStreetMap's public Nominatim allows at most one request per second, requires an identifying User-Agent and forbids bulk jobs. Our API, which sits in front of it, enforces that limit for all users combined. It also limits each network to about 30 requests a minute. Design for this from the start:
- Geocode once, store forever. Addresses rarely move. Geocode at the moment data enters your system, such as a booking form or a CRM import, not every time you display it.
- Debounce user input. Geocode when the user submits, not on every keystroke. Autocomplete on a free geocoder is explicitly against Nominatim's policy. Use a provider that offers it.
- Back off on 429 and 503. Respect the
Retry-Afterheader and use exponential backoff. Never retry a 400, because the request itself needs fixing.
async function withRetry(fn, tries = 4) {
for (let i = 0; ; i++) {
const res = await fn();
if (res.ok || ![429, 502, 503].includes(res.status) || i === tries - 1) return res;
const wait = Number(res.headers.get("Retry-After")) || 2 ** i;
await new Promise((r) => setTimeout(r, wait * 1000));
}
}
If you have tens of thousands of rows, a free API isn't the right tool. Self-host Nominatim with a regional extract, or use a commercial geocoder with a bulk endpoint and a contract. How to geocode an address compares the options.
Storing results with provenance
Store more than the coordinates. A geocode you can't explain later is a liability. For each stored result, keep:
- the exact input string and the normalised version you sent
- latitude, longitude and, where useful, the bbox
- the matched type or rank, so you know whether it was a house or a street
- the provider, the
sourcefield, the licence and the date - whether a person confirmed it, for example by dragging a pin
Provenance pays off in three ways. When the map data improves, you can re-geocode only the coarse matches. When a customer disputes a location, you can see what happened. And you can meet licensing obligations. Results derived from OpenStreetMap are under the ODbL: display “© OpenStreetMap contributors”, and read the OSMF's geocoding guideline before you publish a database built from many results. OpenStreetMap geocoding basics explains the licence in practical terms.
Reverse geocoding calls
Reverse geocoding has one extra control that matters: the level of detail. Our API's zoom parameter (3 = country to 18 = building) chooses which features can answer. Use building level to show an address to the person standing there. Use suburb or city level when you only need context, such as tagging a photo or analysing where demand comes from. That also avoids exposing precise locations. Always compare the returned point with the one you sent. If the nearest address is 400 metres away, say so rather than presenting it as the user's address.
A note on API longevity
APIs outlive the code that first calls them. The original OpenGeocoder published /api/0.1/search in 2012, and blog posts and code linked to it for years. When this site was relaunched, that endpoint was restored with its original array-shaped response. That way, old links still return boxes instead of errors. See the legacy API reference and the project history. If you publish an API, version it in the path and never repurpose old URLs.
Key takeaways
- Send a country filter and ask for several candidates. Check the match type before trusting the first one.
- Treat “no result” as a normal outcome and ask the user. Never substitute a default coordinate.
- Convert bounding-box orderings in one tested function. South is always less than north.
- Geocode once at data entry, cache aggressively, back off on 429 and 503, and keep bulk work off free services.
- Store provenance (input, match type, source, licence, date) alongside every coordinate.