Address Autofill

Address Autofill provides a rich UI for address search and autocomplete functionality for address forms in websites and web apps.

This page includes reference documentation for elements, functions, and types related to Address Autofill and Address Confirmation features of the Mapbox Search JS Web framework.

For installation instructions and a helpful introduction to using Address Autofill in your website or app, see our Web Address Autofill Quickstart Guide.

Automatic Attachment to Form

autofill

Entry point for Mapbox Address Autofill, for use on standard HTML input elements.

Compared to MapboxAddressAutofill, this function automatically attaches to eligible <input> elements in-place.

You must have a Mapbox access token.

Eligible inputs must be a descendant of a <form> element, and the form must have inputs with proper HTML autocomplete attributes. The input itself must be of autocomplete "street-address" or "address-line1"".

If your application works with browser autofill, you may already have this functionality.

Parameters

NameDescription
optionsArg AddressAutofillCollectionOptions AddressAutofillCollectionOptions Object defining options for Address Autofill search behavior and UI.

Returns

AddressAutofillCollectionType

Example

<input type="text" autocomplete="street-address" />
<script>
mapboxsearch.autofill({
  accessToken: 'pk.my.token',
  options: { country: 'us' }
};
</script>
const collection = autofill({
  accessToken: 'pk.my.token',
  options
})

myClientSideRouter.on('route', () => collection.update());
Was this section on autofill helpful?YesNo

AddressAutofillCollection

Underlying collection object class returned by the autofill function.

new AddressAutofillCollection()

Instance Members

The Mapbox access token to use for all requests.

Type
string
Returns
string
Example
autofill.accessToken = 'pk.my-mapbox-access-token';

Options to pass to the underlying AddressAutofillCore interface.

Type
Partial<AddressAutofillOptions>
Returns
Partial<AddressAutofillOptions>
Example
autofill.options = {
 language: 'en',
 country: 'US',
};

The Theme to use for styling the autofill component.

Type
Theme
Returns
Theme
Example
autofill.theme = {
  variables: {
    colorPrimary: 'myBrandRed'
  }
};

The PopoverOptions to define popover positioning.

Type
Partial<PopoverOptions>
Returns
Partial<PopoverOptions>
Example
autofill.popoverOptions = {
  placement: 'top-start',
  flip: true,
  offset: 5
};

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.

Type
(boolean | AddressConfirmOptions)
Example
autofill.confirmOnBrowserAutofill = {
  minimap: true,
  skipConfirmModal: (feature) =>
    ['exact', 'high'].includes(
      feature.properties.match_code.confidence
    )
};

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.

Type
boolean
Example
autofill.browserAutofillEnabled = true;

Methods

Updates autofill collection based on the current DOM state.

Returns
void
Example
collection.update();

Listen for changes to the DOM, and update autofill instances when autofill-able inputs are added/removed.

IMPORTANT: For performance reasons, it is recommended to carefully control when this is called and to call AddressAutofillCollection#unobserve when finished.

Returns
void
Example
collection.observe();

Stop listening for changes to the DOM. This only has an effect if called after AddressAutofillCollection#observe.

Returns
void
Example
collection.unobserve();

Removes all autofill instances and listeners in the document.

Returns
void
Example
collection.remove();

Events

Fired when the user is typing in the input and provides a list of suggestions.

The underlying response from AddressAutofillCore is passed as the event's detail, while the responsible input is passed as the event's target.

Type
AddressAutofillSuggestionResponse
Example
collection.addEventListener('suggest', (event) => {
  const suggestions = event.detail.suggestions;
  const inputEl = event.target;
  // ...
});

Fired when AddressAutofillCore has errored providing a list of suggestions.

The underlying error is passed as the event's detail, while the responsible input is passed as the event's target.

Type
Error
Example
collection.addEventListener('suggesterror', (event) => {
  const error = event.detail;
  const inputEl = event.target;
  // ...
});

Fired when the user has selected a suggestion, before the form is autofilled.

The underlying response from AddressAutofillCore is passed as the event's detail, while the responsible input is passed as the event's target.

Type
AddressAutofillRetrieveResponse
Example
autofill.addEventListener('retrieve', (event) => {
  const featureCollection = event.detail;
  const inputEl = event.target;
  // ...
});
Was this section on AddressAutofillCollection helpful?YesNo

HTML Custom Element

MapboxAddressAutofill

MapboxAddressAutofill, also available as the element <mapbox-address-autofill>, is an element that wraps an address <input> element with intelligent, location-aware autocomplete functionality.

To use this element, you must have a Mapbox access token.

This element must be a descendant of a <form> element, and the form must have inputs with proper HTML autocomplete attributes. If your application works with browser autofill, you may already have this functionality.

new MapboxAddressAutofill()

Example

<form>
  <mapbox-address-autofill access-token="YOUR_MAPBOX_ACCESS_TOKEN">
    <input type="text" name="address" autocomplete="shipping street-address" />
  </mapbox-address-autofill>
</form>

Instance Members

The <input> element wrapped by the autofill component.

Type
HTMLInputElement

The Mapbox access token to use for all requests.

Example
autofill.accessToken = 'pk.my-mapbox-access-token';

Options to pass to the underlying AddressAutofillCore interface.

Type
AddressAutofillOptions
Example
autofill.options = {
 language: 'en',
 country: 'US',
};

The Theme to use for styling the autofill component.

Type
Theme
Example
autofill.theme = {
  variables: {
    colorPrimary: 'myBrandRed'
  }
};

The PopoverOptions to define popover positioning.

Type
PopoverOptions
Example
autofill.popoverOptions = {
  placement: 'top-start',
  flip: true,
  offset: 5
};

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.

Type
(boolean | AddressConfirmOptions)
Example
autofill.confirmOnBrowserAutofill = {
  minimap: true,
  skipConfirmModal: (feature) =>
    ['exact', 'high'].includes(
      feature.properties.match_code.confidence
    )
};

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.

Type
boolean
Example
autofill.browserAutofillEnabled = true;

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
Enable search only when the input value length is more than 3 characters.

search.interceptSearch = (val) => val?.length > 3 ? val : null;

Methods

Focuses the wrapped input element.

Returns
void

Events

Fired when the user is typing in the input and provides a list of suggestions.

The underlying response from AddressAutofillCore is passed as the event's detail.

Type
AddressAutofillSuggestionResponse
Example
autofill.addEventListener('suggest', (event) => {
  const suggestions = event.detail.suggestions;
  // ...
});

Fired when AddressAutofillCore has errored providing a list of suggestions.

The underlying error is passed as the event's detail.

Type
Error
Example
autofill.addEventListener('suggesterror', (event) => {
  const error = event.detail;
  // ...
});

Fired when the user has selected a suggestion, before the form is autofilled.

The underlying response from AddressAutofillCore is passed as the event's detail.

Type
AddressAutofillRetrieveResponse
Example
autofill.addEventListener('retrieve', (event) => {
  const featureCollection = event.detail;
  // ...
});

Fired when the user has changed the <input> text.

The new input value is passed as the event's detail.

Type
string
Example
autofill.addEventListener('input', (event) => {
  if (e.target !== e.currentTarget) return;
  const searchText = event.detail;
  // ...
});
Was this section on MapboxAddressAutofill helpful?YesNo

Functions

getFormAutofillValues

Gets the current input values for address fields given a form and a reference input.

Parameters

NameDescription
form HTMLFormElement HTML form that includes the autocomplete-compliant input fields
ref HTMLInputElement An input element within the desired form address section

Returns

AutofillValueMap: A object mapping WHATWG autocomplete properties to their respective form field values

Example

const form = document.querySelector(form);
const input = form.querySelector('input[autocomplete~="street-address"]')
const valueMap = getFormAutofillValues(form, input);
console.log(valueMap);
// {
//   "street-address": "123 Main",
//   "address-level2": "Boston",
//   "address-level1": "MA",
//   "postal-code": "02129"
// }
Was this section on getFormAutofillValues helpful?YesNo

getAutofillSearchText

Converts an AutofillValueMap to a single line, suitable for display in a text field.

Parameters

NameDescription
snapshot AutofillValueMap An object mapping WHATWG autocomplete attribute values to their corresponding input field values

Returns

string: A concatenated address string

Example

const values = {
  'street-address': '123 Main St',
  'address-level1': 'CA',
  'address-level2': 'San Francisco',
  'address-level3': '',
};

const searchText = getAutofillSearchText(values);
console.log(searchText); // '123 Main St, San Francisco, CA'
Was this section on getAutofillSearchText helpful?YesNo

confirmAddress

A utility that can be run prior to form submission that allows a user to correct or confirm an address.

This parses and compares an address entered into form fields with the closest address suggestion from the Mapbox Address Autofill API. Unless an exact match or a custom comparison callback evaluates to true, the user will be shown a modal dialog asking if they would like to use the suggested address.

When a suggested address is accepted, the values are automatically updated in the form fields.

Parameters

NameDescription
form HTMLFormElement HTML form that includes the autocomplete-compliant input fields
optionsArg AddressConfirmOptions (default {})AddressConfirmOptions Object defining options for Address Autofill API, UI, form parsing, and address comparison

Returns

Promise<AddressConfirmShowResult>: A promise resolving with a result object indicating the decision made by the user

Example

form.addEventListener("submit", async (e) => {
  e.preventDefault();
  const result = await confirmAddress(form, {
    minimap: true,
    skipConfirmModal: (feature) =>
      ['exact', 'high'].includes(
        feature.properties.match_code.confidence
      )
  });
  if (result.type === 'nochange') submitForm();
});
Was this section on confirmAddress helpful?YesNo

Options and Type Definitions

AddressAutofillCollectionOptions

Object defining options for Address Autofill search behavior and UI. Used to configure AddressAutofillCollection

Type

Object

Properties

NameDescription
accessToken string The Mapbox access token to use for all requests.
browserAutofillEnabled boolean 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.

confirmOnBrowserAutofill (boolean | AddressConfirmOptions) 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.
options Partial<AddressAutofillOptions> Options to pass to the underlying AddressAutofillCore interface.
popoverOptions Partial<PopoverOptions> The PopoverOptions to define popover positioning.
theme Theme The Theme to use for styling the autofill component.
Was this section on AddressAutofillCollectionOptions helpful?YesNo

AutofillValueMap

Object mapping WHATWG autocomplete attribute values to corresponding address component strings.

Type

any

Example

{
  "street-address"?: string;
  "address-line1"?: string;
  "address-line2"?: string;
  "address-line3"?: string;
  "address-level4"?: string;
  "address-level3"?: string;
  "address-level2"?: string;
  "address-level1"?: string;
  country?: string;
  "country-name"?: string;
  "postal-code"?: string;
}
Was this section on AutofillValueMap helpful?YesNo

AddressConfirmOptions

Object defining options for Address Autofill API, UI, form parsing, and address comparison

Type

Object

Properties

NameDescription
accessToken string Mapbox access token used for the Address Autofill and Static Image APIs
footer (boolean | string) 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.
minimap (boolean | ConfirmationMinimapOptions) 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.
options Partial<ValidationOptions> Address Autofill API configuration options ValidationOptions
sections Array<string> 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.
skipConfirmModal function (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.
theme Theme CSS variables and icons
Was this section on AddressConfirmOptions helpful?YesNo

ValidationOptions

Type

Object

Properties

NameDescription
bbox (string | LngLatBoundsLike) Limit results to only those contained within the supplied bounding box.
country string An ISO 3166 alpha-2 country code to be returned.

If not specified, results will not be filtered by country.

language string The IETF language tag to be returned.

If not specified, en will be used.

proximity (string | LngLatLike) Bias the response to favor results that are closer to this location.

When both ValidationOptions#proximity and ValidationOptions#origin are specified, origin is interpreted as the target of a route, while proximity indicates the current user location.

Was this section on ValidationOptions helpful?YesNo

ConfirmationMinimapOptions

Styling and theming options for a MapboxAddressMinimap embedded inside a confirmation dialog.

Type

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
  }
});
Was this section on ConfirmationMinimapOptions helpful?YesNo

AddressConfirmShowResult

Object indicating the decision made by the user during address confirmation when using confirmAddress.

Type

({type: "change", feature: AddressAutofillFeatureSuggestion} | {type: "nochange"} | {type: "cancel"})
Was this section on AddressConfirmShowResult helpful?YesNo