@duabalabs/maps
v0.1.0
Published
Pick a location on a Mapbox map: address search on submit, a draggable pin, “Use my location”, reverse geocoding, and Ghana's Plus Codes and digital addresses. A headless core plus React components.
Maintainers
Readme
@duabalabs/maps
Pick a location on a Mapbox map. Type an address and search, check the spot on a map, drag the pin to the exact place, or press Use my location. Built for Ghana first.
- A headless core with no React and nothing that touches
windowon import:Place;- search providers (Mapbox direct, or your own functions);
- a search controller: one request per search (on Enter or a Search button), a superseded search aborted, repeats answered from a small cache;
- resolvers, reverse geocoding and Ghana's border;
- Static Images URLs.
- React components (
@duabalabs/maps/react, React 18.2+ or 19,'use client'):<LocationPicker>;<LocationPreview>;- the hooks
usePlaceSearch,useReverseGeocodeanduseDeviceLocation.
- Plain CSS on your app's semantic CSS variables. It looks native in Duaba apps, light and dark, and needs no Tailwind.
The pin is the point of the picker. In Ghana, Mapbox knows areas, towns and regions, but no streets and no landmarks (see Costs). Search gets the map to the neighbourhood. The person drags the pin to the door, and couriers price from that pin.
Install
npm install @duabalabs/maps mapbox-glreact and mapbox-gl are peer dependencies.
- mapbox-gl is downloaded only when a map is first shown. The picker loads it with
import(), so your bundler puts it in its own chunk. - A page that never shows a map never loads it.
- An app that uses only the core (no React, no map) doesn't need either.
Use it
'use client';
import { mapboxProvider, type Place } from '@duabalabs/maps';
import { LocationPicker } from '@duabalabs/maps/react';
import '@duabalabs/maps/styles.css';
const token = process.env.NEXT_PUBLIC_MAPBOX_TOKEN; // or import.meta.env.VITE_MAPBOX_TOKEN
const provider = token ? mapboxProvider({ token }) : null; // make it once, outside the component
export function DeliveryAddress() {
const [place, setPlace] = useState<Place | null>(null);
return <LocationPicker value={place} onChange={setPlace} provider={provider} mapboxToken={token} />;
}onChange(place, change) gets a Place:
{ latitude, longitude, label, address, city, region, country, source: 'search' | 'map' | 'device' | 'resolver', id?, kind? }countryis the ISO code (GH).change.reasonis one ofsearch,resolver,drag,tap,keyboard,deviceorreverse.
A pin moved on the map, or set by Use my location, comes in twice:
- First, its coordinates only.
- Then the same point with its words, with
reason: 'reverse', once they are known. If the pin moved again first, that answer is dropped.
So apps should fill empty fields from later calls, rather than overwrite what the person typed.
Vite
// .env.local: VITE_MAPBOX_TOKEN=pk.…
const token = import.meta.env.VITE_MAPBOX_TOKEN as string | undefined;Import @duabalabs/maps/styles.css once, from the component that uses the picker or from your
global styles.
Next.js (App Router)
- The picker is a client component. Use it from a file that starts with
'use client'. - Import
@duabalabs/maps/styles.cssthere, or inapp/layout.tsx. - Use
NEXT_PUBLIC_MAPBOX_TOKEN. - The core is safe in server components:
staticMapUrl,isInGhana,formatCoordinates… LocationPreviewrenders on the server too.
mapbox-gl's own stylesheet is fetched from Mapbox's CDN, at the loaded version, when the map first
shows. If your app already imports mapbox-gl/dist/mapbox-gl.css, pass mapboxCss={false}.
With a Content-Security-Policy, allow:
https://api.mapbox.cominscript-src,style-srcandconnect-src;https://events.mapbox.comandhttps://*.tiles.mapbox.cominconnect-src;blob:inworker-src.
Searching through your own server
An app that keeps its geocoding key on its server passes its own functions. The picker still sends one request per search, aborts a superseded one, caches repeats and runs resolvers:
import { customProvider } from '@duabalabs/maps';
const provider = customProvider({
id: 'sellub-server',
country: 'GH', // filled in when a result has none
search: (query, { signal }) => api.searchGhanaPlaces(query, { signal }), // [{ label, address, city, region, latitude, longitude }]
reverse: (latitude, longitude) => api.ghanaPlaceAt(latitude, longitude),
});Any word may be missing from a result; each one becomes a full Place. A reverse answer always
keeps the exact point asked about. The map still needs a public token (mapboxToken). Without one,
the picker is search plus Use my location, with no map.
Showing a saved location
<LocationPreview latitude={5.5606} longitude={-0.1824} label="Osu, Accra" mapboxToken={token} markerColor="#1f6f43" />- One Static Images picture with the pin, the address, the coordinates and an Open in Google Maps link. No JavaScript map.
- Without a token, or if the image fails (for example a URL restriction), it shows a placeholder with the same caption.
API
Core: @duabalabs/maps
| | |
| --- | --- |
| mapboxProvider(options) | Geocoding API v6 from the browser. Options: token; country ('gh'); bbox (Ghana's); proximity ('ip', or a point; the picker sends the pin or the map's centre); language ('en'); types (address up to region); limit (5); autocomplete (true: the last word may match as a prefix, so "Adenta" finds "Adentan"; same price); permanent (false); fetch; baseUrl. |
| customProvider({ id, search, reverse?, country? }) | Your own functions as a provider. |
| createPlaceSearch(options) | Search without UI, on submit. Options: provider, resolvers, minLength (2, for Ho and Wa), limit, cache. Methods: search(query, { proximity }) (one request, sent at once; a newer search aborts it and it rejects with an AbortError), clear, cancel, subscribe, getState, setOptions. |
| reverseGeocode(provider, lat, lng, { signal, source, cache }) | The words for a point, keeping the exact point. |
| coordinatesResolver(), parseCoordinates(text) | Pasted coordinates and maps links. |
| getDeviceLocation(options) | The browser's position, or a DeviceLocationError with code: unsupported, insecure, denied, unavailable or timeout. |
| isInGhana(lat, lng, toleranceKm = 1) | Inside Ghana's border, from Natural Earth 1:10m simplified to 1 km. A point within 1 km of the border passes, so beaches pass; central Lomé and Abidjan don't. |
| isInBounds, isValidPoint | Box and range checks. |
| GHANA_BBOX, GHANA_CENTER, ACCRA | Constants. |
| staticMapUrl(options) | A Static Images URL with a pin. |
| toPlace, pointPlace, formatCoordinates, googleMapsUrl, samePoint, zoomForKind, placeFromMapboxV6 | Helpers. |
| createPlaceCache, MapsRequestError (status: 401 bad token, 403 URL restriction, 429 rate limit), isAbortError | Utilities. |
React: @duabalabs/maps/react
<LocationPicker> takes value, onChange and provider, plus these props:
- Search:
resolvers(default: pasted coordinates),minLength,proximity,inputId,autoFocus, andlabelId/descriptionIdwhen the app draws its own visible label and help text (the input is then named and described by them, and the picker's hidden label is left out). - Map:
mapboxToken(no token, no map),mapStyle(defaultmapbox://styles/mapbox/streets-v12),showMap,initialBounds(default Ghana's box: with no value the map fits it),initialCenterandinitialZoom(used instead when given),cooperativeGestures(default true: two fingers to pan on phones),markerColor(default the theme's--primary),mapOptions. - Loading:
loadMapbox(defaultimport('mapbox-gl')),mapboxCss. - Behaviour:
restrictTo(defaultisInGhana;nullallows anywhere),showDeviceLocation,disabled. - Look and words:
strings,classNames,className, and anydivprop.
How it behaves:
- Searching. Nothing is sent while the person types. Enter in the field, or the Search button, sends one search. Enter never submits a form the picker sits in.
- Results. A resolver's answer (pasted coordinates, a digital address) goes straight to the pin. The provider's answers are listed below the field: a WAI-ARIA listbox, keyboard navigable. ↓ from the field moves into the list; there ↑ ↓ Home End move, Enter or Space picks, and Escape goes back to the field. A click picks too. Picking moves the pin and closes the list. A live region announces the count.
- The pin is focusable: the arrow keys nudge it by 10 px, or 50 px with Shift.
- A point outside
restrictTois refused with a message. A dragged pin goes back to where it was. - Map loading. The map is created, which is the billable map load, only when it scrolls into view.
- Flights. It flies to a chosen result in at most 2.5 seconds, or jumps if the trip would take longer.
- Resizing. When its container is resized, it keeps the pin in sight.
<LocationPreview> takes latitude, longitude, label, mapboxToken, zoom, width,
height, mapStyle, markerColor, showLink, strings and classNames.
The hooks are for apps that draw their own UI:
usePlaceSearch(options):{ search(query, request?), results, loading, error, status, query, answeredBy, clear, cancel }. A newersearchaborts the one in flight.useReverseGeocode(provider, point, { source, debounceMs }):{ point, place, status, error }.useDeviceLocation():{ locate, status, position, error, reset }.
Resolvers: digital addresses and other codes
A resolver claims typed text before the search provider sees it. This is how GhanaPostGPS codes
(GA-123-4567), Plus Codes and pasted coordinates join the picker.
interface LocationResolver {
id: string; // unique; names it in cache keys
label?: string; // what its codes are called, e.g. "GhanaPost GPS"
test(input: string): boolean; // cheap and synchronous: is this text mine?
resolve(input: string, signal: AbortSignal): Promise<Place | null>;
fromPoint?(latitude: number, longitude: number, signal?: AbortSignal): Promise<string | null>;
}How the search uses them:
- When a search is submitted, each resolver's
testruns in order. The first that returns true owns the text, and the provider is not asked. - What
resolvereturns is the only answer, and the picker puts the pin straight on it. Null means nothing found. Answers are cached like searches. signalaborts when a newer search starts. Pass it tofetch.
Writing one:
- Return
source: 'resolver'. - Leave unknown words null. Once the place is chosen, the picker asks the provider's
reversefor them. fromPointis optional. With it, the picker shows the pinned point's code under the map (GhanaPost GPS: GA-123-4567), for any pin, however it was placed.
The package ships one resolver, coordinatesResolver():
- It reads
5.6037, -0.1870,5.6037° N, 0.1870° Wand Google or Apple Maps links. - It swaps a longitude-first pair when only the swap lands in Ghana.
- It needs no request. It is the picker's default
resolvers.
To add your own, keep it in the list:
<LocationPicker resolvers={[ghanaPostGpsResolver, coordinatesResolver()]} … />Ghana: Plus Codes and digital addresses (@duabalabs/maps/ghana)
A separate entry (about 14 KB gzipped, with its tables), so apps that don't use it don't load it.
import { coordinatesResolver, mapboxProvider } from '@duabalabs/maps';
import { createGhanaPostGpsResolver, createPlusCodeResolver } from '@duabalabs/maps/ghana';
const provider = mapboxProvider({ accessToken });
const resolvers = [
createPlusCodeResolver(), // "6CQXHR43+C6", "HR43+C6 Accra", plus.codes links
createGhanaPostGpsResolver({ provider }), // "GA-183-8164", "ga1838164"
coordinatesResolver(),
];
<LocationPicker provider={provider} resolvers={resolvers} … />- Plus Codes (Google's Open Location Code): exact to about 3 m and worked out offline, with no
request. Google Maps shows one for any point; long-press a spot and copy it. A short code with
a town (
HR43+C6 Accra) is completed from a built-in list of Ghanaian towns. WithfromPoint, the picker shows the Plus Code of whatever point is pinned. - GhanaPostGPS digital addresses: typed any way (
ga 183 8164,GA1838164) and tidied toGA-183-8164. Its region and district come from Ghana Post's published code guide. Ghana Post's own code-to-point service is private, and its terms forbid reuse, so the resolver never calls it. Instead:lookup(optional): your own address book of points your users confirmed for a code. A hit puts the pin exactly there.- Otherwise, with a
provider, the map opens on the code's district (kind: 'district'), and the picker asks the person to drag the pin to their door. Save that confirmed pin, and add it to your book with the person's consent.
parseGhanaPostGps(text)gives the parts, errors and warnings for a form field of its own.
Both resolvers return a point only. The picker's reverse lookup fills in the words.
Tokens
Use one public token (pk.…) per app and environment. Create it at
account.mapbox.com/access-tokens.
Scopes. Give it only the public scopes these features need:
styles:read: load a map style;fonts:read: the map's labels;styles:tiles: Static Images.
Mapbox's docs name no scope for the Geocoding API; it works with any public token. Never put a
secret (sk.…) token in a browser.
URL restrictions (Mapbox's guide):
- Add each production origin to the token:
sellub.com,dashboard.sellub.com. - An entry also allows its subdomains and paths, so
sellub.comcoverswww.sellub.com. - Wildcards and IP addresses are not supported. A token takes at most 100 URLs.
- Requests from
localhostare refused unlesslocalhostis on the list. Use a separate development token withlocalhost, never the production one. - Netlify deploy previews (
deploy-preview-12--site.netlify.app) can't be matched without allowing all ofnetlify.app. Give previews the development token, or no token: they then work without a map. - Shops on their own domains need each domain on the list, or they get no map and no search (403).
- Restrictions read the
Refererheader. A page withReferrer-Policy: no-referrerorsame-origingets 403s.strict-origin-when-cross-origin, the browsers' default, works.LocationPreviewsets it on its image. - Mapbox calls restrictions "a best-effort mitigation". Watch usage on the token's Statistics page.
Rotate a token by creating a new one, deploying it, then deleting the old one.
Costs
Prices are from mapbox.com/pricing, read on 2026-11-04. Each free tier is per Mapbox account, per month, and is shared by every app on that account.
| Service | Free each month | Then (per 1,000) |
| --- | --- | --- |
| Map loads for Web (GL JS) | 50,000 loads | $5.00 to 100k · $4.00 to 200k · $3.00 to 1M · $2.50 to 5M |
| Geocoding API, temporary (v5 and v6, same price) | 100,000 requests | $0.75 to 500k · $0.60 to 1M · $0.45 above |
| Geocoding API, permanent (permanent=true) | none | $5.00 to 500k · $4.00 above |
| Static Images API | 50,000 requests | $1.00 to 500k · $0.80 to 1M · $0.60 above |
Why Geocoding v6
The picker searches on submit: one request per search, nothing while typing. So the question is which of Mapbox's per-request searches is cheapest and good enough in Ghana:
- Geocoding v6 (temporary): 100,000 requests free each month, then $0.75 per 1,000. Every answer carries coordinates, so choosing a result costs nothing more. v5 is the same price.
- Geocoding, permanent: no free tier, $5.00 per 1,000.
- Search Box API: its session pricing (500 sessions free, then $3.00 per 1,000) is for
/suggestand/retrievewhile typing, which the picker doesn't do. Its per-request/forwardisn't priced separately on the pricing page. What it adds is points of interest, and in Ghana it has none of the landmarks.
On 2026-11-04 we ran the same Ghana searches through Geocoding v6 and Search Box, in Mapbox's own
playgrounds, with country=gh and proximity at Accra:
- Areas and towns came back the same from both: East Legon, Osu, Spintex, Dansoman, Cantonments, Kumasi, Kasoa.
- Landmarks came back from neither: Accra Mall, Kotoka airport, Makola, Kejetia, the University of Ghana, Shell, Melcom. Search Box's points of interest exist abroad, not in Ghana.
- Neither has streets: Oxford Street, Liberation Road and Independence Avenue found nothing.
- Geocoding v5 lost its points of interest too ("POI data has been removed from the Geocoding v5
API"), so
types=poiin an old v5 call now does nothing.
So the picker uses Geocoding v6 for search and for reverse lookups. If Mapbox's Ghana landmark coverage improves, switching is a provider swap behind the same picker.
What each action costs
The cost after each free tier is used up, at the first paid tier:
| Action | Mapbox calls | Cost |
| --- | --- | --- |
| Open the picker with a map | 1 map load, when the map scrolls into view | $0.005 |
| Open the picker, never scroll to the map | none | $0 |
| Type an address | none | $0 |
| Search (Enter or the Search button) | 1 geocoding request; the same text again in the same visit comes from the cache | $0.00075 |
| Choose a search result | none (it has its coordinates) | $0 |
| Paste coordinates, or another resolver's code | none for coordinates; a digital-address resolver may call its own service | $0 |
| Drag or tap the pin, or press Use my location | 1 reverse request after the pin settles (350 ms); the browser's location is free | $0.00075 |
| Show a LocationPreview | 1 Static Images request per browser, cached 12 hours | $0.001 |
Monthly estimate
We assume each location pick costs:
- 1 map load;
- 2 searches (a first try and a refined one) and 1 reverse request: 3 geocoding requests;
- 2 preview views (for example the seller's settings card and an order page).
| Picks a month | Map loads | Geocoding requests | Static images | Mapbox bill | | --- | --- | --- | --- | --- | | 1,000 | 1,000 (free) | 3,000 (free) | 2,000 (free) | $0 | | 10,000 | 10,000 (free) | 30,000 (free) | 20,000 (free) | $0 | | 100,000 | 100,000: 50,000 × $5.00/1k = $250 | 300,000: 200,000 × $0.75/1k = $150 | 200,000: 150,000 × $1.00/1k = $150 | $550 |
Geocoding's free tier covers about 33,000 picks a month. At 100,000 picks the map is nearly half
the bill. To spend less, show LocationPreview until the person asks to adjust the pin.
Keeping results
Mapbox's temporary geocoding is for the current session. In Mapbox's FAQ: "You cannot store the coordinate results for future use". Each response carries the same notice.
- The package's cache is in memory only, for 10 minutes.
- An app that saves a chosen place stores its point and words. A pin the person dragged or set with their device is their own point. A search result saved as it came is Mapbox's.
- If that matters for your use, pass
permanent: truetomapboxProvider. That is $5.00 per 1,000 requests from the first, and needs a card or contract on the account. Or ask Mapbox.
Styling
- Import
@duabalabs/maps/styles.css. The parts read your app's semantic variables:--background,--foreground,--card,--popover,--border,--input,--primary,--muted,--muted-foreground,--accent,--ring,--radius,--destructive-soft-foreground,--warning-soft,--elevation-md. - Each variable has a light fallback, and a dark one under
prefers-color-scheme: dark, for apps without them. In a Duaba app the theme's.darkclass switches everything. - Restyle a part with
classNames(search,input,clear,submit,results,listbox,option,actions,locate,map,summary,message), or with itsdata-slot([data-slot="location-picker-input"]). - Set the map's height with
--dmaps-map-height(320px by default, shorter on phones). - For a dark map, pass a dark style when your theme is dark:
mapStyle="mapbox://styles/mapbox/dark-v11".LocationPreviewtakesmapStyle="mapbox/dark-v11". - Every visible string is in
strings, with English defaults (DEFAULT_PICKER_STRINGS). The strings that take values are functions:accuracyHint(meters),resultsAnnouncement(count),coordinates(lat, lng).
Develop
npm install
npm test # vitest: the core, and LocationPicker in jsdom with mapbox-gl mocked
npm run typecheck
npm run build # dist/: ESM + CJS + types for both entries, and styles.css
npm pack # a tarball to try in an app before publishingPublishing
.github/workflows/publish-maps.yml publishes a new version from develop through npm Trusted
Publishing.
- npm can only trust a workflow for a package that already exists. Publish the first version
by hand:
npm login, thencd packages/maps && npm publish --access public. - Then, on npmjs.com, go to the package's Settings → Trusted Publisher → GitHub Actions and enter:
- organization
duabalabs; - repository
duaba-ui; - workflow
publish-maps.yml; - environment blank.
- organization
- After that, bump
versionand push todevelop.
Licence
MIT. Ghana's outline is from Natural Earth (public domain). The icons are Lucide's shapes (ISC).
See LICENSE. The Ghana entry includes a port of Google's Open Location Code (Apache-2.0) and a
GeoNames town list (CC BY 4.0); see THIRD_PARTY_NOTICES.md.
