Address Autofill
- Components
- Hooks
- Types
- AddressAutofillRefType
- AddressAutofillOptions
- AddressConfirmOptions
- PopoverOptions
- AddressAutofillSuggestion
- AddressAutofillFeatureSuggestion
- AddressAutofillSuggestionResponse
- AddressAutofillRetrieveResponse
- AddressAutofillFeatureContextComponent
- LngLatLike
- LngLatBoundsLike
- ConfirmationMinimapOptions
- ValidationOptions
- MatchCode
Address Autofill provides a rich UI for address search and autocomplete functionality for address forms in React-based web apps.
This page includes reference documentation for the Address Autofill and Address Confirmation components, hooks, and types in the Mapbox Search JS React framework.
For installation instructions and a helpful introduction to using Address Autofill in your React app, see our React Address Autofill Quickstart Guide.
Components
AddressAutofill
<AddressAutofill> is a React component that wraps an address
<input> element with intelligent, location-aware autocomplete functionality.
To use this element, you must have a Mapbox access token.
This component must be a descendant of a <form>, and the form
must have inputs with proper HTML autocomplete attributes. If your application works with browser autofill, you may already have
this functionality.
Internally, this wraps the <mapbox-address-autofill> element.
Props
| Name | Description |
|---|---|
| The Mapbox access token to use for all requests. | |
optionsPartial<AddressAutofillOptions> | Options to pass to the underlying AddressAutofillCore interface. |
| The Theme to use for styling the autofill and confirmation dialog components. | |
popoverOptionsPartial<PopoverOptions> | The PopoverOptions to define popover positioning. |
| If true, forms autofilled by the browser will prompt the confirmAddress dialog for user confirmation. An AddressConfirmOptions object can also be passed to prompt confirmAddress with custom options. Defaults to false. | |
| Enables the browser's autocomplete popup to show during the first two typed characters while Mapbox results are suppressed. Defaults to false.
Note: Due to varying specifications, efforts to suppress browser autocomplete behavior may not work on all browsers. | |
childrenReact.ReactChild | Children to render inside the autofill component. This
must
include
an
<input>
element
with either autocomplete type
"street-address"
or
"address-line1"
.
|
Callback for when the
<input>
value changes.
| |
onSuggestfunction (res: AddressAutofillSuggestionResponse): void | Fired when the user is typing in the input and provides a list of suggestions. The underlying response from AddressAutofillCore is passed. |
onSuggestErrorfunction (error: Error): void | Fired when AddressAutofillCore has errored providing a list of suggestions. The underlying error is passed. |
onRetrievefunction (res: AddressAutofillRetrieveResponse): void | Fired when the user has selected a suggestion, before the form is autofilled. The underlying response from AddressAutofillCore is passed. |
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 { AddressAutofill } from '@mapbox/search-js-react'
export function Component() {
const [value, setValue] = React.useState('');
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<form>
<AddressAutofill accessToken={'YOUR_MAPBOX_ACCESS_TOKEN'}>
<input
autoComplete="shipping address-line1"
value={value}
onChange={handleChange}
/>
</AddressAutofill>
</form>
);
}
Hooks
useAddressAutofillCore
A React hook that returns a AddressAutofillCore instance.
Parameters
| Name | Description |
|---|---|
| Your Mapbox access token. |
Returns
AddressAutofillCoreExample
import { useAddressAutofillCore } from '../src';
const autofill = useAddressAutofillCore({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });
const response = await autofill.suggest('1600 pennsylvania ave nw', {
sessionToken: 'test-123'
});
console.log(response);
// { suggestions: [...], attribution: '...' };
Related
useConfirmAddress
A React hook that returns a form ref and a function to show the address confirmation modal
Parameters
| Name | Description |
|---|---|
Returns
UseConfirmAddressObjectExample
import { useConfirmAddress } from '@mapbox/search-js-react';
export function Autofill(): React.ReactElement {
const { formRef, showConfirm } = useConfirmAddress({
footer: 'My custom footer'
});
const handleSubmit = React.useCallback(async () => {
const result = await showConfirm();
console.log(result);
}, [showConfirm]);
return (
<div>
<form
ref={formRef}
style={{ display: 'flex', flexDirection: 'column', marginTop: 30 }}
>
<AddressAutofill
...
>
</div>
);
}
Related
Types
AddressAutofillRefType
Methods available on a ref when attached to the AddressAutofill component.
ObjectProperties
| Name | Description |
|---|---|
focusany |
AddressAutofillOptions
Options used by AddressAutofillCore and useAddressAutofillCore to control the location, language, country, and limit of results. All properties are optional.
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. | |
The
IETF language tag
to be returned. If not specified,
en
will be used.
| |
The number of results to return, up to
10
.
| |
Bias the response to favor results that are closer to this location. Provide a point coordinate provided as a
LngLatLike
, or use the string
ip
to use the requester's IP address.
| |
If enabled, street results may be returned in addition to addresses. Defaults to
true
.
|
AddressConfirmOptions
Object defining options for Address Autofill API, UI, form parsing, and address comparison
ObjectProperties
| Name | Description |
|---|---|
| Mapbox access token used for the Address Autofill and Static Image APIs | |
Custom footer text appearing at the bottom of the confirmation modal dialog.
If
true
or left undefined, the default footer text will be used.
If
false
, the footer will not be shown.
| |
| If true, a static minimap showing the suggested address location will be displayed in the modal dialog. If an object, a minimap will be displayed with the specified styling and theming configuration. Defaults to false. | |
optionsPartial<ValidationOptions> | Address Autofill API configuration options ValidationOptions |
An array of section names used within form element
autocomplete
attributes to identify and group one address section from another, e.g. "section-shipping" or "section-billing".
These are often used when a single
contains multiple logical sections.
If left undefined, all discoverable sections will be processed.
| |
skipConfirmModalfunction (feature: AddressAutofillFeatureSuggestion): boolean | A callback used to pre-confirm an address and skip the UI modal.
The feature argument contains all address components, as well as an
MatchCode
object,
which are used to express the confidence of an address match.
The callback must return a boolean, with
true
indicating that the address has been pre-confirmed,
and the UI modal will be skipped and will not be presented to the end-user.
If left undefined, this defaults to skipping showing the modal when the validated feature's match code
returns an "exact" match.
|
| CSS variables and icons |
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'. |
AddressAutofillSuggestion
An AddressAutofillSuggestion object represents a suggestion
result from the Mapbox Address Autofill API.
Suggestion objects are "part one" of the two-step interactive autofill experience. Suggestion objects do not include geographic coordinates.
To get the coordinates of the result, use AddressAutofillCore#retrieve.
For tracking purposes, it is useful for any follow-up requests based on this suggestion to include same SessionToken as the original request.
ObjectProperties
| Name | Description |
|---|---|
A point accuracy metric for the returned address feature. Can be one of
rooftop
,
parcel
,
point
,
interpolated
,
intersection
,
street
.
| |
| Action block of the suggestion result. contains id to execute retrieve | |
| Address level 1 from the WHATWG Autocomplete Specification | |
| Address level 2 from the WHATWG Autocomplete Specification | |
| Address level 3 from the WHATWG Autocomplete Specification | |
| Address line 1 from the WHATWG Autocomplete Specification | |
| Address line 2 from the WHATWG Autocomplete Specification | |
| Address line 3 from the WHATWG Autocomplete Specification | |
| An array of context objects representing the hierarchy of encompassing parent features for a given feature. | |
| Long form country name, for example: "United States" | |
| The short form country name, for example: "us". This follows the ISO 3166 alpha-2 country code specification. | |
| Additional details, such as city and state for addresses. | |
| The name of the feature. | |
| The full address of the suggestion. | |
| The IETF language tag of the feature. | |
| The name of the Maki icon associated with the feature. | |
Feature id. The
mapbox_id
uniquely identifies a feature in the Mapbox search database.
| |
| An object describing the level of confidence that the given response feature matches the address intended by the request query. Includes boolean flags denoting matches for each address sub-component. | |
| The feature name, as matched by the search algorithm. | |
| Address metadata fields of the feature.
Includes the short form country name, for example: "us". This follows the ISO 3166 alpha-2 country code specification. | |
| A string representing the feature in the requested language, if specified, and its full result hierarchy. | |
| An array of strings representing the geographic feature type of the feature. Possible values include "address" and "secondary_address". | |
| Postal code. |
Example
const autofill = new AddressAutofillCore({ accessToken: 'pk.my-mapbox-access-token' });
const sessionToken = new SessionToken();
const result = await search.autofill('Washington D.C.', { sessionToken });
if (result.suggestions.length === 0) return;
const suggestion = result.suggestions[0];
const { features } = await autofill.retrieve(suggestion, { sessionToken });
doSomethingWithCoordinates(features);
AddressAutofillFeatureSuggestion
An AddressAutofillFeatureSuggestion object represents GeoJSON
suggestion results from the Mapbox Address Autofill API.
As per the Mapbox Address Autofill API, this will always be Point.
anyExample
const featureSuggestion = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0,0]
},
properties: {
feature_name: 'Washington D.C.',
}
};
Static Members
AddressAutofillSuggestionResponse
Response object returned when calling the suggest method of AddressAutofillCore
ObjectProperties
| Name | Description |
|---|---|
| The attribution data for results. | |
| The returned suggestion objects. |
AddressAutofillRetrieveResponse
Response object returned when calling the retrieve method of AddressAutofillCore
ObjectProperties
| Name | Description |
|---|---|
| The attribution data for results. | |
| The returned feature objects. |
AddressAutofillFeatureContextComponent
Object representing one level of hierarcy among encompassing parent features for a given AddressAutofillSuggestion.
ObjectProperties
| Name | Description |
|---|---|
An identifier prefixed with the component type, for example
country.123
.
| |
| The unique Mapbox ID of the context feature. | |
| A string representing the feature in the requested language, if specified. | |
| The Wikidata identifier for the returned feature. |
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]];
ConfirmationMinimapOptions
Styling and theming options for a MapboxAddressMinimap embedded inside a confirmation dialog.
Partial<Pick<MapboxAddressMinimap, ("defaultMapStyle" | "theme" | "mapStyleMode" | "satelliteToggle")>>Example
const result = await confirmAddress(form, {
accessToken: 'abc-123',
minimap: {
defaultMapStyle: ['mapbox', 'outdoors-v11'],
theme: { icons: { marker: MARKER_SVG } },
mapStyleMode: 'default',
satelliteToggle: true
}
});
ValidationOptions
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. | |
| The
IETF language tag
to be returned.
If not specified, | |
| Bias the response to favor results that are closer to this location.
When both ValidationOptions#proximity and ValidationOptions#origin are specified, |
MatchCode
An object describing the level of confidence that the given response feature matches the address intended by the request query.
ObjectProperties
| Name | Description |
|---|---|
An indication of how well the
address_number
component of the feature matches the query.
| |
| An overall confidence level for how well the feature matches the query. | |
An indication of how well the
country
component of the feature matches the query.
| |
An indication of how well the
locality
component of the feature matches the query.
| |
An indication of how well the
place
component of the feature matches the query.
| |
An indication of how well the
postcode
component of the feature matches the query.
| |
An indication of how well the
region
component of the feature matches the query.
| |
An indication of how well the
secondary_address
component of the feature matches the query.
| |
An indication of how well the
street
component of the feature matches the query.
|