The plan
- Geocode every branch once, on the server, and keep the coordinates.
- Let the visitor search with autocomplete, or use their location.
- Pre-filter branches by straight-line distance in the browser.
- Rank the closest ten by drive time with one distance-matrix call, through your server.
- Show the result as a list and as pins on a GeoDesh map.
Steps 1 and 4 run on your server so your API key never reaches the browser. Step 2 can go through your server too; in this tutorial it does.
1. Geocode the branches once
import fs from 'node:fs/promises';
const branches = JSON.parse(await fs.readFile('branches.json', 'utf8'));
for (const b of branches) {
if (b.lat) continue;
const url = 'https://geodesh.com/v1/geocode?address=' + encodeURIComponent(b.address);
const r = await fetch(url, { headers: { 'x-api-key': process.env.GEODESH_KEY } }).then((x) => x.json());
const hit = r.data?.[0];
if (hit) Object.assign(b, { lat: hit.location.lat, lng: hit.location.lng });
else console.warn('Not found:', b.address);
}
await fs.writeFile('branches.json', JSON.stringify(branches, null, 2));With 200 branches this is 200 geocodes, ৳36 at list price, paid once. Check the warnings and fix any address the geocoder could not place.
2. A small server for search and ranking
Two routes: one forwards autocomplete, the other ranks branches. Both add the key on the server.
import express from 'express';
import branches from './branches.json' with { type: 'json' };
const app = express();
app.use(express.json());
const KEY = process.env.GEODESH_KEY;
const gd = (path, init = {}) => fetch('https://geodesh.com' + path, { ...init, headers: { 'x-api-key': KEY, 'content-type': 'application/json', ...init.headers } }).then((r) => r.json());
app.get('/api/suggest', async (req, res) => {
const q = String(req.query.q ?? '').slice(0, 80);
if (q.length < 3) return res.json([]);
const r = await gd('/v1/places/autocomplete?input=' + encodeURIComponent(q) + '&lat=23.78&lng=90.40');
res.json((r.data ?? []).slice(0, 5));
});
const km = (a, b) => Math.hypot(a.lat - b.lat, (a.lng - b.lng) * Math.cos((a.lat * Math.PI) / 180)) * 111;
app.post('/api/nearest', async (req, res) => {
const from = { lat: Number(req.body.lat), lng: Number(req.body.lng) };
const near = branches.filter((b) => b.lat).sort((a, b) => km(from, a) - km(from, b)).slice(0, 10);
const r = await gd('/v1/routes/matrix', { method: 'POST', body: JSON.stringify({ origins: [from], destinations: near.map((b) => ({ lat: b.lat, lng: b.lng })) }) });
const row = r.data?.rows?.[0]?.elements ?? [];
const ranked = near.map((b, j) => ({ ...b, secs: row[j]?.durationInTraffic?.value ?? row[j]?.duration?.value ?? null, text: row[j]?.durationInTraffic?.text ?? row[j]?.duration?.text ?? '' }))
.sort((a, b) => (a.secs ?? 1e9) - (b.secs ?? 1e9));
res.json(ranked);
});
app.listen(3000);3. The React component
The map comes from the GeoDesh Map SDK script tag in index.html. The component creates the map once and redraws pins when the results change.
import { useEffect, useRef, useState } from 'react';
export default function StoreLocator() {
const box = useRef(null), map = useRef(null), pins = useRef([]);
const [q, setQ] = useState(''), [sugs, setSugs] = useState([]), [list, setList] = useState([]);
useEffect(() => {
map.current = new window.AtlasMap(box.current, { apiKey: import.meta.env.VITE_GEODESH_BROWSER_KEY, center: [23.78, 90.4], zoom: 12 });
return () => map.current?.destroy();
}, []);
useEffect(() => {
const t = setTimeout(async () => setSugs(q.length >= 3 ? await fetch('/api/suggest?q=' + encodeURIComponent(q)).then((r) => r.json()) : []), 250);
return () => clearTimeout(t);
}, [q]);
async function pick(s) {
setSugs([]); setQ(s.mainText);
const ranked = await fetch('/api/nearest', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(s.location) }).then((r) => r.json());
setList(ranked);
pins.current.forEach((p) => p.remove());
pins.current = ranked.map((b, i) => map.current.addMarker({ lat: b.lat, lng: b.lng, title: b.name, subtitle: b.text, label: String(i + 1) }));
map.current.fitBounds([s.location, ...ranked.map((b) => ({ lat: b.lat, lng: b.lng }))]);
}
return (
<div className="locator">
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search your area" aria-label="Search your area" />
{sugs.length > 0 && <ul>{sugs.map((s) => <li key={s.placeId}><button onClick={() => pick(s)}>{s.mainText} <small>{s.secondaryText}</small></button></li>)}</ul>}
<ol>{list.map((b) => <li key={b.id}>{b.name}: {b.text || 'time unavailable'}</li>)}</ol>
<div ref={box} style={{ height: 480 }} />
</div>
);
}4. Using the visitor’s location
Add a “Near me” button that reads navigator.geolocation.getCurrentPosition and sends the coordinates to /api/nearest. This skips autocomplete entirely, which saves money and works well on phones.
What it costs
| Per search | Calls | List price |
|---|---|---|
| Autocomplete (debounced) | ~3 | ৳0.36 |
| Distance matrix | 1 | ৳0.60 |
| Map load | 1 per page view | ৳0.25 |
20,000 searches a month comes to about ৳24,200 at list prices, before the ৳5,000 free credit and plan discounts. The “Near me” path costs only the matrix call.
Polish
- Show opening hours from your own data next to each branch.
- Add a “Directions” link per branch that opens your app’s route view.
- Restrict the browser key to your origin and the maps scope.
- Cache matrix answers for popular areas for a few minutes.
See the store locator solution, the Places API and pricing.
Search engines and your locator
A locator built only in JavaScript is invisible to search. Give each branch its own simple page with its name, address, hours and phone number in plain HTML, and link to those pages from the locator list. People searching for a branch name then land on the right page, and the locator handles everyone else.
Keeping branch data fresh
Branches open, close and move. Keep your branch list in one place your team edits, re-run the geocoding script whenever an address changes, and show a “last updated” date in the locator footer. If a branch is listed on the map with hours and a phone number, link to its place details so visitors always see current hours.
Accessibility and mobile details
- Give the search box a visible label or an
aria-label, and make suggestions reachable with the keyboard. - Show results as a list as well as pins: many visitors never touch the map.
- On phones, put the list first and the map below, and offer a “Near me” button.
- Show the drive time in words (“12 min”) rather than distance alone; in traffic it is what people care about.
Testing before launch
- Search five areas you know well and check the order of branches makes sense.
- Try a misspelling and a Bangla area name written in English.
- Turn off location permission and check the page still works.
- Watch the request count in the console while you test, to confirm debouncing works.
Frequently asked questions
Do I need a server for this?
Yes, a small one: it keeps your key private and lets you cache answers. Any back end works, including serverless functions.
Can I use Leaflet instead of the GeoDesh SDK?
Yes. Point Leaflet at GeoDesh tiles and add your own markers; the ranking code stays the same.