Geocoding
Geocoding provides a rich UI search component, allowing users to forward and reverse geocode search and control a Mapbox GL JS map.
This page includes reference documentation for the Geocoding components and hooks in the Mapbox Search JS React framework.
For installation instructions and a helpful introduction to using Geocoding in your React app, see our React Search Box Quickstart Guide.
Components
Geocoder
<Geocoder> is a React component that provides an interactive geocoder,
powered by the Mapbox Geocoding API.
To use this element, you must have a Mapbox access token.
Internally, this wraps the <mapbox-geocoder> element.
Props
| Name | Description |
|---|---|
| The Mapbox access token to use for all requests. | |
optionsPartial<GeocodingOptions> | Options to pass to the underlying GeocodingCore interface. |
| Options defining the behavior of web component or its underlying search functionality. | |
| The Theme to use for styling the geocoder. | |
popoverOptionsPartial<PopoverOptions> | The PopoverOptions to define popover positioning. |
| The input element's placeholder text. The default value may be localized if GeocodingOptions#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
GeocoderProps#mapboxgl
also be set.
| |
mapboxglany | A
mapbox-gl
instance to use when creating
Markers
. Required if
GeocoderProps#marker
is
true
.
|
| Value to display in the geocoder. | |
| Callback for when the value changes. | |
onSuggestfunction (res: GeocodingResponse): void | Fired when the user is typing in the input and provides a list of suggestions. The underlying response from GeocodingCore is passed. |
onSuggestErrorfunction (error: Error): void | Fired when GeocodingCore has errored providing a list of suggestions. The underlying error is passed. |
onRetrievefunction (res: GeocodingFeature): void | Fired when the user has selected a suggestion. The underlying feature from GeocodingCore 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 { Geocoder } from "@mapbox/search-js-react";
export function Component() {
const [value, setValue] = React.useState('');
const handleChange = (d) => {
setValue(d);
};
return (
<Geocoder
options={{
proximity: {
lng: -122.431297,
lat: 37.773972,
},
}}
value={value}
onChange={handleChange}
accessToken="YOUR_MAPBOX_ACCESS_TOKEN"
/>
);
}
Hooks
useGeocodingCore
A React hook that returns a GeocodingCore instance.
Parameters
| Name | Description |
|---|---|
| Your Mapbox access token. |
Returns
GeocodingCoreExample
import { useGeocodingCore } from '@mapbox/search-js-react';
const geocodingCore = useGeocodingCore({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });
const response = await geocodingCore.forward('1600 pennsylvania ave nw', {
limit: 1
});
console.log(response);
// { type: 'FeatureCollection', features: [...], attribution: '...', url: '...' };
Related
Types
GeocoderRefType
Methods available on a ref when attached to the Geocoder component.
ObjectProperties
| Name | Description |
|---|---|
focusany | |
searchany |
GeocodingOptions
Options object for configuring GeocodingCore, mapped to Geocoding API parameters.
ObjectProperties
| Name | Description |
|---|---|
| When autocomplete is enabled, results will be included that start with the requested string, rather than just responses that match it exactly.
Defaults to true. | |
| Limit results to only those contained within the supplied bounding box. | |
| Limit results to one or more countries. Permitted values are ISO 3166 alpha 2 country codes separated by commas. | |
| An IETF language tag that controls the language of the text supplied in responses, and also affects result scoring. | |
The number of results to return, up to
10
.
Defaults to 5. | |
| Permanent geocodes are used for use cases that require storing
data indefinitely. If 'true', requests will be made with permanent enabled.
Separate billing for permanent geocoding will apply.
If undefined or 'false', the geocoder will default to use temporary geocoding. Temporary geocoding results are not allowed to be cached. For questions related to permanent resource usage and billing, contact Mapbox sales. | |
| Bias the response to favor results that are closer to this location.
Provided as two comma-separated coordinates in longitude,latitude order, or the string | |
types(string | Set<FeatureTypes>) | Filter results to include only a subset (one or more) of the available feature types. Multiple options can be comma-separated. |
Available worldviews are:
cn
,
in
,
jp
,
us
. If a worldview is not set,
us
worldview boundaries will be returned.
|
GeocodingResponse
A GeocodingResponse object represents a returned data object from the Mapbox Geocoding API.
ObjectProperties
| Name | Description |
|---|---|
| Attributes the results of the Mapbox Geocoding API to Mapbox. | |
| The returned feature objects. | |
type | "FeatureCollection"
, a GeoJSON type from the
GeoJSON specification
.
|
GeocodingFeature
A GeocodingFeature object represents a GeoJSON feature result from the Mapbox Geocoding API.
Legal terms:
Due to legal terms from our data sources, results from the Mapbox Geocoding API should use the permanent=true flag
if the results are to be cached/stored in a customer database. Otherwise, results should be used ephemerally and not persisted.
This permanent policy is consistent with the Mapbox Terms of Service and failure to comply may result in modified or discontinued service.
Additionally, 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.
anyStatic Members
Related
MapboxGeocoderComponentOptions
Options to configure component-specific Search behavior
ObjectProperties
| Name | Description |
|---|---|
customSearchfunction (text: string): Promise<Array<GeocodingFeature>> | A function accepting the query string which performs supplemental search results on top of those from the Mapbox Geocoding API. Expected to return a Promise which resolves to an array of GeoJSON-like Features as described in the Mapbox Geocoding API . |
| 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'. |
LngLatLike
A LngLat object, an array of two numbers representing longitude and latitude,
or an object with lng and lat or lon and lat properties.
(LngLat | [number, number] | {lng: number, lat: number} | {lon: number, lat: number})Example
const v1 = new LngLat(-122.420679, 37.772537);
const v2 = [-122.420679, 37.772537];
const v3 = {lon: -122.420679, lat: 37.772537};
LngLatBoundsLike
A LngLatBounds object, an array of LngLatLike objects in [sw, ne] order, or an array of numbers in [west, south, east, north] order.
(LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number])Example
const v1 = new LngLatBounds(
new LngLat(-73.9876, 40.7661),
new LngLat(-73.9397, 40.8002)
);
const v2 = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
const v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
FeatureTypes
Geographic feature data types for the Mapbox Geocoding API.
("country" | "region" | "postcode" | "district" | "place" | "locality" | "neighborhood" | "street" | "block" | "address" | "secondary_address")