Geocode addresses with Node.js.
Convert addresses to latitude and longitude from Node.js using the built-in fetch API, keep your key safe behind an Express endpoint, and process lists of addresses.
1. Get an API key
Create a free account, verify your email and create a key in the dashboard. Put it in an environment variable on your server:
export GEOCODING_API_KEY="your-key-here"The code uses the built-in fetch, so Node.js 20 or newer needs no extra packages.
2. Geocode an address
// geocode.mjs (Node.js 20+, no dependencies)
const API_URL = 'https://api.geocoding.info/search';
export async function geocode(address, { country } = {}) {
const key = process.env.GEOCODING_API_KEY;
if (!key) throw new Error('Set GEOCODING_API_KEY');
const params = new URLSearchParams({
q: address, format: 'json', limit: '1',
addressdetails: '1', 'accept-language': 'en', key,
});
if (country) params.set('countrycodes', country);
const response = await fetch(`${API_URL}?${params}`, {
signal: AbortSignal.timeout(20_000),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(`Geocoding failed: HTTP ${response.status} ${body.error?.code ?? ''}`.trim());
}
const [best] = await response.json(); // results array, best match first
if (!best) return null; // nothing matched
return {
lat: Number(best.lat), // lat/lon arrive as strings
lon: Number(best.lon),
label: best.display_name,
country: best.address?.country_code,
};
}
console.log(await geocode('Badshahi Mosque, Lahore', { country: 'pk' }));Running node geocode.mjs prints something like { lat: 31.588126, lon: 74.3093528, label: 'Badshahi Mosque, Fort Road, …, Pakistan', country: 'pk' }. The optional country option limits matches to one country, which avoids results in the wrong place for common street names.
3. Call it from your web app without exposing the key
Never put your API key in browser JavaScript. Instead, add a small endpoint to your backend and let the browser call that. With Express:
// server.mjs: keep the API key on the server
import express from 'express';
import { geocode } from './geocode.mjs';
const app = express();
app.get('/api/geocode', async (req, res) => {
const address = String(req.query.q ?? '').trim();
if (!address || address.length > 200) {
return res.status(400).json({ error: 'Provide an address of up to 200 characters.' });
}
try {
res.json((await geocode(address)) ?? { found: false });
} catch {
res.status(502).json({ error: 'Geocoding is temporarily unavailable.' });
}
});
app.listen(3000, () => console.log('Listening on http://localhost:3000'));Your front end can now call /api/geocode?q=…. Add caching and your own rate limiting before exposing the endpoint publicly.
4. Geocode a list of addresses
For a batch, send requests sequentially and pause between them so you stay within your plan's per-second limit:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function geocodeAll(addresses) {
const results = [];
for (const address of addresses) { // one request at a time
try {
results.push({ address, ...(await geocode(address)) });
} catch (error) {
results.push({ address, error: error.message });
}
await sleep(1000); // respect your plan's per-second limit
}
return results;
}Failed lookups are recorded rather than stopping the whole batch. See the geocoding API reference for every parameter and error code.
Frequently asked questions
Can I call the geocoding API directly from the browser?
It works technically, but anyone could copy your API key from the page and use your quota. Call the API from your Node.js backend and have the browser call your own endpoint instead.
Why does the result use Number(best.lat)?
The API returns latitude and longitude as decimal strings, exactly as Nominatim provides them. Converting them to numbers is needed before you pass them to a map library or do calculations.
How do I get more than one result?
Increase the limit parameter, for example limit=5, and return the whole array instead of only the first item. This is useful for autocomplete-style pickers where the user chooses the right place.
More developer guides
Map data © OpenStreetMap contributors, available under the Open Database License. Results come from Nominatim and depend on mapped coverage.