Search Box
Search Box provides a rich UI for single-box location search, allowing your users to search for addresses and points of interest by place name, address, or category.
This page includes reference documentation the Search Box components and hooks in the Mapbox Search JS React framework.
For installation instructions and a helpful introduction to using Search Box in your React app, see our React Search Box Quickstart Guide.
Components
SearchBox
<SearchBox> is a React component that provides an interactive search box,
powered by the Mapbox Search Box API.
To use this element, you must have a Mapbox access token.
Internally, this wraps the <mapbox-search-box> element.
Props
| Name | Description |
|---|---|
| The Mapbox access token to use for all requests. | |
optionsPartial<SearchBoxOptions> | Options to pass to the underlying SearchBoxCore interface. |
| Options defining the behavior of web component or its underlying search functionality. | |
| The Theme to use for styling the search box. | |
popoverOptionsPartial<PopoverOptions> | The PopoverOptions to define popover positioning. |
| The input element's placeholder text. The default value may be localized if SearchBoxOptions#language is set. | |
mapmapboxgl.Map | If specified, the map will be centered on the retrieved suggestion. |
If
true
, a
Marker
will be added to the map at the location of the user-selected result using a default set of Marker options. If the value is an object, the marker will be constructed using these options. If
false
, no marker will be added to the map. Requires that
SearchBoxProps#mapboxgl
also be set.
| |
mapboxglany | A
mapbox-gl
instance to use when creating
Markers
. Required if
SearchBoxProps#marker
is
true
.
|
| Value to display in the search box. | |
| Callback for when the value changes. | |
onSuggestfunction (res: SearchBoxSuggestionResponse): void | Fired when the user is typing in the input and provides a list of suggestions. The underlying response from SearchBoxCore is passed. |
onSuggestErrorfunction (error: Error): void | Fired when SearchBoxCore has errored providing a list of suggestions. The underlying error is passed. |
onRetrievefunction (res: SearchBoxRetrieveResponse): void | Fired when the user has selected a suggestion. The underlying response from SearchBoxCore is passed. |
onClearfunction (): void | Fired when the user has cleared the search box. |
onBlurfunction (): void | Fired when the user has blurred the search box. |
interceptSearchfunction (value: string): string | A callback providing the opportunity to validate and/or manipulate the input text before it triggers a search, for example by using a regular expression.
If a truthy string value is returned, it will be passed into the underlying search API. If
null
,
undefined
or empty string is returned, no search request will be performed.
|
Example
import { SearchBox } from "@mapbox/search-js-react";
export function Component() {
const [value, setValue] = React.useState('');
const handleChange = (d) => {
setValue(d);
};
return (
<SearchBox
options={{
proximity: {
lng: -122.431297,
lat: 37.773972,
},
}}
value={value}
onChange={handleChange}
accessToken="YOUR_MAPBOX_ACCESS_TOKEN"
/>
);
}
Hooks
useSearchBoxCore
A React hook that returns a SearchBoxCore instance.
Parameters
| Name | Description |
|---|---|
| Your Mapbox access token. |
Returns
SearchBoxCoreExample
import { useSearchBoxCore } from '@mapbox/search-js-react';
const searchBoxCore = useSearchBoxCore({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });
const response = await searchBoxCore.suggest('1600 pennsylvania ave nw', {
sessionToken: 'test-123'
});
console.log(response);
// { suggestions: [...], attribution: '...', url: '...' };
Related
useSearchSession
A React hook that returns a SearchSession instance.
Parameters
| Name | Description |
|---|---|
Returns
SearchSession: Related
Types
SearchBoxRefType
Methods available on a ref when attached to the SearchBox component.
ObjectProperties
| Name | Description |
|---|---|
focusany | |
searchany |
SearchBoxOptions
Options object for configuring SearchBoxCore, mapped to Search Box API parameters.
ObjectProperties
| Name | Description |
|---|---|
| Limit results to only those contained within the supplied bounding box. | |
| An
ISO 3166 alpha-2 country code
to be returned.
If not specified, results will not be filtered by country. | |
eta_type | Used to estimate the time of arrival from the location specified in
SearchBoxOptions#origin
.
The only allowed value for this parameter is navigation. This parameter, along with SearchBoxOptions#origin and SearchBoxOptions#navigation_profile, is required for ETA calculations. ETA calculations will incur additional latency. |
| The
IETF language tag
to be returned.
If not specified, | |
The number of results to return, up to
10
.
| |
navigation_profile( | The navigation routing profile to use for distance/eta calculations.
For distance calculations, both SearchBoxOptions#navigation_profile and SearchBoxOptions#origin must be specified. For ETA calculations: SearchBoxOptions#navigation_profile, SearchBoxOptions#origin, and SearchBoxOptions#eta_type must be specified. |
| The location from which to calculate distance.
This parameter may incur additional latency.
When both SearchBoxOptions#proximity and SearchBoxOptions#origin are specified, For distance calculations, both SearchBoxOptions#navigation_profile and SearchBoxOptions#origin must be specified. For ETA calculations: SearchBoxOptions#navigation_profile, SearchBoxOptions#origin, and SearchBoxOptions#eta_type must be specified. | |
| Limit results to those that belong to one or more categories, provided as a comma-separated list. | |
| A comma-separated list of canonical category names that limits POI results to those that are not part of the given categories. | |
| Bias the response to favor results that are closer to this location.
When both SearchBoxOptions#proximity and SearchBoxOptions#origin are specified, | |
| A comma-separated list of rich metadata providers to include in a suggestion result. | |
| A polyline encoded linestring describing the route to be used for searching.
Both polyline5 and polyline6 precision are accepted, but must be specified using the SearchBoxOptions#route_geometry parameter. | |
| Passed in conjunction with a route polyline describing its precision. Options are polyline or polyline6. If this parameter is not provided with a
SearchBoxOptions#route
, the default is polyline.
Accurate results depend on including the correct route_geometry for the SearchBoxOptions#route provided. | |
| This indicates that the user intends to perform a higher cost search-along-route request.
This should be included when SearchBoxOptions#route is included and should have a value of isochrone. | |
| Maximum detour in estimated minutes from route. | |
| Limit results to one or more types of features. If no types are specified, all possible types may be returned.
Reference: https://docs.mapbox.com/api/search/search-box/#administrative-unit-types |
SearchBoxSuggestionResponse
A SearchBoxSuggestionResponse object represents a returned data object from the suggest endpoint of the Mapbox Search Box API.
ObjectProperties
| Name | Description |
|---|---|
| The attribution data for results. | |
| The returned suggestion objects. |
SearchBoxRetrieveResponse
A SearchBoxRetrieveResponse object represents a returned data object from the /retrieve endpoint of the Mapbox Search Box API.
ObjectProperties
| Name | Description |
|---|---|
| The attribution data for results. | |
| The returned feature objects. |
SearchBoxSuggestion
A SearchBoxSuggestion object represents a suggestion result from the Mapbox Search Box API.
SearchBoxSuggestion objects are "part one" of the two-step interactive search experience, and include useful information about the result, such as: SearchBoxSuggestion#name, SearchBoxSuggestion#full_address, and SearchBoxSuggestion#maki.
SearchBoxSuggestion objects do not include geographic coordinates. To get the coordinates of the result, use SearchBoxCore#retrieve.
For tracking purposes, it is useful for any follow-up requests based on this suggestion to include same SessionToken as the original request.
Reference: https://docs.mapbox.com/api/search/search-box/#response-get-suggested-results
ObjectProperties
| Name | Description |
|---|---|
| The distance added to an input route by including the given suggestion, in meters. | |
| The estimated time added to an input route by including the given suggestion, in minutes. | |
| The address of the result containing the address number and street. | |
| The brand name of the result, if it is a POI and is applicable. | |
| The canonical brand ID of the result, if it is a POI and is applicable. | |
| The context of the feature. This context has layers that follow the Administrative unit types . | |
An approximate distance to the
origin
location, in meters. Only provided when
origin
and
navigation_profile
are used in the request.
| |
The estimated time of arrival from the origin point to the feature, in minutes.
Only provided when
eta_type
,
origin
, and
navigation_profile
are used in the request.
If an address is not on the road network, an ETA will not be provided.
| |
external_idsany | An object containing the IDs of the feature found in external databases, with the keys being the data source names and the values being the IDs. |
The type of the result. For POIs, this will be
poi
.
For categories, this will be
category
.
For address-type results, the global context hierarchy is used (
country
,
region
,
postcode
,
district
,
place
,
locality
,
neighborhood
,
address
).
See the
Administrative unit types section
for details about these types.
| |
| The full address of the result, which concatenates SearchBoxSuggestion#address and SearchBoxSuggestion#place_formatted . | |
| An IETF language tag indicating the language of the result. | |
| A string representing an associated Maki icon to use for this result. | |
| The id to use with SearchBoxCore#retrieve to obtain full feature details. | |
metadataany | An object containing additional metadata for the feature, if applicable. |
| The name of the feature. | |
| The preferred name of the feature, if different than SearchBoxSuggestion#name . | |
| A formatted string of result context comprised of the place, region, country, and postcode. | |
| An array including the POI categories the result falls into, if it is a POI. |
Example
const search = new SearchBoxCore({ accessToken: 'pk.my-mapbox-access-token' });
const sessionToken = new SessionToken();
const result = await search.suggest('Washington D.C.', { sessionToken });
if (result.suggestions.length === 0) return;
const suggestion = result.suggestions[0];
const { features } = await search.retrieve(suggestion, { sessionToken });
doSomethingWithCoordinates(features);
SuggestionJSONContext
Raw JSON form of a suggestion result's "context" from the Mapbox Search Box API.
Reference: https://docs.mapbox.com/api/search/search-box/#response-get-suggested-results
ObjectProperties
| Name | Description |
|---|---|
addressContextEntry | The address of the result including the address number and street |
address_numberContextEntry | The address number of the result |
countryany | The country of the result |
districtContextEntry | The district of the result |
localityContextEntry | The locality of the result |
neighborhoodContextEntry | The neighborhood of the result |
placeContextEntry | The place of the result |
postcodeContextEntry | The postcode of the result |
regionany | The region of the result |
streetContextEntry | The street of the result |
SearchBoxFeatureSuggestion
A SearchBoxFeatureSuggestion object represents a GeoJSON suggestion result from the Mapbox Search Box API.
Feature suggestions are "part two" of the two-step interactive search experience and includes geographic coordinates. Multiple feature suggestions may be returned from a single search query, for example in an airport with multiple terminals.
As per the Mapbox Search Box API, this will always be Point.
Legal terms:
The Mapbox Terms of Service states any rendering of a feature suggestion must be using Mapbox map services (for example, displaying results on Google Maps or MapKit JS is not allowed).
Disclaimer:
The failure of Mapbox to exercise or enforce any right or provision of these Terms will not constitute a waiver of such right or provision.
anyExample
const featureSuggestion = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0,0]
},
properties: {
name: 'Washington D.C.',
}
};
Related
SearchBoxAdministrativeUnitTypes
Administrative unit types for the Mapbox Search Box API.
("country" | "region" | "postcode" | "district" | "place" | "locality" | "neighborhood" | "street" | "address" | "block")Related
MapboxSearchBoxComponentOptions
Options to configure component-specific Search behavior
ObjectProperties
| Name | Description |
|---|---|
| Allow the user to query a coordinate string (e.g. "lng,lat") to get a reverse search result. | |
customSearchfunction (text: string): Promise<Array<SearchBoxSuggestion>> | A function accepting the query string which performs supplemental search results
on top of those from the Mapbox Search Box API. Expected to return a Promise
which resolves to an array of suggestions as described in the
Mapbox Search Box API
.
Additionally, each suggestion must include a
_geometry
property matching the
"geometry" object format specified in the
retrieved Feature
format.
|
| If true, the coordinates in the query string are expected to be (lat,lng) instead of (lng,lat). | |
If
false
, animating the map to a selected result is disabled. If
true
(default), animating the map will use the default animation parameters. If an object, it will be passed as
options
to the map
flyTo
method.
|
PopoverOptions
Options controlling the display of the Popover used in AddressAutofill, MapboxSearchBox, and MapboxGeocoder.
ObjectProperties
| Name | Description |
|---|---|
| If true, the popover will flip to the opposite side of the reference element to try to keep it in view when scrolling out of frame. Defaults to false. | |
| The distance gap between the popover and the reference element. Defaults to 5px. | |
placement( | Positions the popover above or below the reference element. Defaults to 'bottom-start'. |