dart_mapbox_search 2.0.0
dart_mapbox_search: ^2.0.0 copied to clipboard
A production-ready Dart SDK for the Mapbox Search Box, Geocoding, and Places APIs.
dart_mapbox_search
A production-ready, community-maintained Dart SDK for Mapbox search and geocoding.
The public surface tracks the current Search Box API v1, Geocoding API v6, and Places Details API v1. It provides typed immutable request and response models, local validation, Search Box session management, request metadata, predictable exceptions, raw JSON retention, and dependency-injected HTTP transport.
Developed with π and maintained by coderave
Important notes #
- 2.0.0 is an intentional breaking redesign. The global initializer,
MapboxSearchClient, nested legacy clients,MapboxSearchResult, and old response hierarchy were removed. See the migration guide. - Mapbox storage rules differ by API. Search Box and Places Details results
are temporary-use data. Geocoding results are temporary unless the request
uses
permanent: trueand the Mapbox account is eligible for permanent geocoding. Confirm the current Mapbox terms before persisting any result. - Places Details v1 and Geocoding entrances are public previews. Their upstream contracts can change before general availability.
- Protect tokens appropriately. Never distribute a secret Mapbox token.
Restrict public tokens to the minimum scopes and allowed origins or URLs.
Places Details requests require a token with the
places:readscope. - This package covers Mapbox search, geocoding, and place details. Routing, Matrix, Directions, Navigation, Maps, and Tiles APIs are outside its scope.
Feature matrix #
| API | Capability | Support | Example |
|---|---|---|---|
| Search Box v1 | Interactive suggest and retrieve sessions | Stable | Session |
| Search Box v1 | One-off forward search and current POI filters | Stable | Forward |
| Search Box v1 | Category catalog and category browsing | Stable | Categories |
| Search Box v1 | Reverse search | Stable | Reverse |
| Search Box v1 | Search along route, including long-route POST | Stable | Route |
| Search Box v1 | Distance and ETA enrichment | Stable | ETA |
| Geocoding v6 | Text and structured forward geocoding | Stable | Text / structured |
| Geocoding v6 | Reverse geocoding | Stable | Reverse |
| Geocoding v6 | Mixed batch geocoding, up to 1,000 queries | Stable | Batch |
| Geocoding v6 | Permanent-result request mode | Stable | Permanent |
| Geocoding v6 | Building entrances and routable points | Public preview | Entrances |
| Places Details v1 | Single and batch POI details | Public preview | Places |
| Shared transport | Custom client, gateway, metadata, and typed errors | Stable | Configuration / errors |
Install #
dart pub add dart_mapbox_search
The package requires Dart 3.8 or newer.
Quick start #
import 'package:dart_mapbox_search/dart_mapbox_search.dart';
Future<void> findCoffee(String accessToken) async {
final MapboxSearch mapbox = MapboxSearch(accessToken: accessToken);
try {
final MapboxResponse<SearchBoxFeatureCollection> response =
await mapbox.searchBox.forward(
'coffee',
options: SearchBoxForwardOptions(
proximity: MapboxCoordinateProximity(
MapboxPoint(longitude: 13.405, latitude: 52.52),
),
limit: 5,
),
);
for (final SearchBoxFeature feature in response.data.features) {
print('${feature.properties.name}: ${feature.geometry.point}');
}
} finally {
mapbox.close();
}
}
Run the complete quick start with an environment variable:
MAPBOX_ACCESS_TOKEN=pk... dart run example/main.dart
See the runnable quick-start example.
Client lifecycle and configuration #
Create one MapboxSearch instance per application or service and reuse it.
The instance shares one connection pool and token across searchBox,
geocoding, and places. Calling close() releases an internally created
HTTP client and is safe more than once. Calls after closing fail with
StateError.
An injected http.Client remains caller-owned by default. Set
closeClient: true to transfer ownership. The constructor also accepts
timeout, immutable defaultHeaders, a custom absolute baseUri for a
compatible gateway, and a deterministic sessionTokenGenerator.
See custom client and gateway configuration.
Responses, raw JSON, and errors #
Every network method returns Future<MapboxResponse<T>>. A response exposes
typed data, HTTP statusCode, immutable lowercase headers, a Mapbox
requestId, and parsed rateLimit metadata. Every response model extends
MapboxJsonModel and retains its complete immutable payload in json, so
newly added server fields remain available before the SDK adds typed getters.
Unknown feature, status, and metadata strings are retained instead of being
forced through closed enums. Required GeoJSON discriminators are validated.
Failures are thrown as typed exceptions:
MapboxApiExceptionfor non-2xx API responses, including status, headers, request ID, parsed details, and raw body.MapboxTimeoutExceptionwhen the configured request timeout expires.MapboxNetworkExceptionwhen the HTTP client cannot complete the request.MapboxDecodeExceptionwhen a successful response does not match the documented JSON shape.ArgumentError,RangeError, orStateErrorfor invalid local usage.
Access tokens are redacted in URIs stored in transport exceptions. See response metadata and complete error handling.
Search Box sessions #
Use one SearchBoxSession per active user search. It generates a UUIDv4,
reuses it for each suggest call and the matching retrieve, then rotates the
token after a successful retrieval. reset() abandons the current local
session and rotates immediately. A retrieval without a successful suggestion
fails locally.
Mapbox ends a Search Box session after retrieval, 50 suggestions, or 180 seconds, whichever occurs first. Do not share a token between concurrent user searches. The session helper does not retain suggestions or results.
See interactive suggest and retrieve.
Complete feature and example index #
Every supported operation and meaningful request mode is demonstrated below.
The linked files are analyzed package examples that import only the public
library entrypoint and read MAPBOX_ACCESS_TOKEN at runtime.
Search Box API v1 #
- Interactive
suggestandretrieve, metadata attribute sets, and token rotation - One-off forward search with language, spatial, country, feature-type, POI, availability, rating, price, response-field, ranking, and autocomplete filters
- List the live category catalog and browse one canonical category
- Reverse search with language, country, type, closed-POI, and result-limit controls
- Search along a route with query-string GET and long-route form POST delivery
- Matrix-backed distance and ETA enrichment for forward search, category browsing, suggestions, and retrieval
Search Box suggest returns coordinate-free suggestions. Call retrieve with
the selected mapboxId and the same session token to obtain geometry.
forward, category, and reverse are one-off operations and do not use a
session token. Category IDs are runtime data; use listCategories instead of
hard-coding display names where practical.
Long encoded routes can exceed safe URL lengths. Set
MapboxRoute.delivery to MapboxRouteDelivery.body for forward or
category; the SDK sends the route as form data while keeping the other
search-along-route options in the query.
Geocoding API v6 #
- Free-form forward geocoding with autocomplete, spatial filters, languages, types, worldview, and public-preview entrances
- Structured forward geocoding with address components and match confidence
- Reverse geocoding with country, language, type, worldview, and result-limit controls
- Mixed text, structured, and reverse batch geocoding with up to 1,000 queries
- Temporary and permanent forward, structured, reverse, and batch request modes
Geocoding requests are validated before transport: free-form queries are limited to 256 characters and 20 tokens, language lists to 20 unique tags, forward limits to 10, reverse limits to 5, and reverse requests with more than one result to exactly one feature type.
Set entrances: true on a text or structured forward request to request
public-preview building entrance and routable-point data when coverage exists.
Batch-level permanent applies to every query in that request.
Places Details API v1 public preview #
- Retrieve complete details for one Mapbox ID
- Retrieve 1β100 unique IDs and handle partial HTTP 206 results, missing IDs, and unprocessed IDs
Places Details enriches POI Mapbox IDs with typed address, category, score,
coordinate, routable point, building, photo, telemetry, and category-specific
attribute data. Category-specific attributes remain available as immutable raw
JSON. The preview endpoint requires places:read and does not permit permanent
result storage.
Transport and observability #
- Inject an HTTP client, configure ownership, timeout, default headers, and a custom base URI
- Inspect status, headers, request ID, rate-limit metadata, and retained raw response JSON
- Handle API, timeout, network, decode, and local validation failures
API design #
- All supported functionality is exported from
package:dart_mapbox_search/dart_mapbox_search.dart;src/imports are private implementation details. - Request option collections and response payloads are copied into immutable structures.
- Coordinate, bounding-box, query, filter, limit, route, ETA, batch, and structured-address constraints fail locally before a billable request.
- Request enums represent documented wire values. Response kinds, statuses,
metadata, and complete payloads stay forward-compatible through raw strings
and
MapboxJsonModel.json. - HTTP 200β299 responses, including Places partial-success HTTP 206, are
decoded as successful
MapboxResponse<T>values.
Development #
dart pub get
dart format --output=none --set-exit-if-changed .
dart analyze
dart test
The CI workflow also enforces 100% line coverage, generated API documentation, and a clean package publish dry run.
Contributing and security #
See CONTRIBUTING.md before proposing a change. Report security issues privately according to SECURITY.md.
License #
dart_mapbox_search is distributed under the
GNU General Public License v3.0.