All tutorials

Swiftcomplete JavaScript Integration: Add Address Autocomplete to Web Forms

intermediate

The Swiftcomplete API provides real-time address suggestions as you type, eliminating typos and mistakes and reducing the time it takes to find accurate postal addresses.

If you need help integrating our Swiftcomplete API into your website or application, contact us, and one of our product experts will help you get started.

Authentication

Each request must be authenticated with a Swiftcomplete API key, which you can create in your Swiftcomplete account:

1. Sign in if you’re already registered, or create a Swiftcomplete account if you’re new to the service.

2. Go to the API section and create a Swiftcomplete API Key.

Integration options

Once you’ve created a Swiftcomplete API Key, you can either:

  1. Integrate directly using the Swiftcomplete Address Autocomplete API. Build a custom integration with full control over address lookup, formatting, and logic using our RESTful API.
  2. Use the Swiftcomplete JavaScript Integration. Add address autocomplete to your website or checkout page quickly by installing our lightweight JavaScript SDK.
  3. Install a ready-made plugin or integrations for your e-commerce platform.
    Get started instantly with our official integrations for platforms like WooCommerce, BigCommerce, Ecwid and Shopify(available soon as plugin)

JavaScript integration

The JavaScript Swiftcomplete integration is a code snippet that can be included on your website or in your checkout to provide address search with real-time suggestions as you type.

1Add the script to load the Swiftcomplete JavaScript file

Firstly, copy & paste the code snippet into the <head> section of your HTML, before the closing </head> tag.

Note: Make sure you only copy the code snippet once, even if you have multiple address fields on your page.

<script>!function (e, t, c) {
    e.swiftcomplete = e.swiftcomplete || {};
    var s = t.createElement("script");
    s.async = !0, s.src = c;
    var r = t.getElementsByTagName("script")[0];
    r.parentNode.insertBefore(s, r)
		}(window, document, "https://assets.swiftcomplete.com/js/swiftlookup.js");
</script>
Copied
2Add Swiftcomplete functionality to a text field

Now copy this script and paste it directly after the previous code snippet, before the closing <head> tag.

To get the script running, replace INSERT_KEY_HERE with your Swiftcomplete API key, and replace INSERT_TEXT_FIELD_ID_HERE with the ID of an existing textbox on your page.

The script initialises Swiftcomplete on your existing textbox, restricts searching to Great Britain and logs the record and coordinates to the developer console when you select a result from the list of autocomplete suggestions.

<script type="text/javascript">
    /*#########################################
    Insert your API key here to run the demo:
    #########################################*/
    var SWIFTCOMPLETE_API_KEY = "INSERT_KEY_HERE";
    var SWIFTCOMPLETE_SEARCH_FIELD_ID = "INSERT_TEXT_FIELD_ID_HERE";

    function initialiseSwiftcomplete() {
        swiftcomplete.runWhenReady(function () {
            // Attach search functionality to existing field
            swiftcomplete.controls["Search field"] = new swiftcomplete.SwiftLookup({
                field: document.getElementById(SWIFTCOMPLETE_SEARCH_FIELD_ID),
                key: SWIFTCOMPLETE_API_KEY,
                searchFor: ""
            });

            // Restrict searching to just Great Britain (leave this out to search all available countries)
            swiftcomplete.controls["Search field"].setCountries('gb');

            // Add event listener to listen for when a result has been selected
            document.getElementById(SWIFTCOMPLETE_SEARCH_FIELD_ID).addEventListener('swiftcomplete:Swiftcomplete:selected', function (e) {
                // Record
                console.log(e.detail.result.record);

                // Coordinates
                console.log(e.detail.result.geometry.centre);
            }, false);
        });
    }

    window.addEventListener("load", initialiseSwiftcomplete, false);
</script>
Copied
3Test your integration

Refresh your page, and try searching in your existing text field. The record and coordinates are printed to the developer console when you click a result from the list of suggestions.

4Migration Guide: Transitioning to Swiftcomplete

Swiftcomplete has released an updated, branded integration library — Swiftcomplete — which replaces the legacy “Places” API and associated scripts. This new version offers improved reliability, updated styling, and streamlined hosting via a modern CDN.

All new integrations should now use the Swiftcomplete library. Existing integrations will remain functional but are no longer recommended for new development.

✅ Use These Updated Resources

Embed the following Swiftcomplete resources in your integration:

<!-- JavaScript -->
<script src="https://assets.swiftcomplete.com/js/swiftlookup.js"></script>

<!-- CSS -->
<link rel="stylesheet" href="https://assets.swiftcomplete.com/css/swiftlookup.css" />
Copied

These files are hosted on a CDN for improved performance and reliability and are aligned with the latest Swiftcomplete branding and data models.

🚫 Do Not Use (Deprecated)

Please update any documentation or integration that references the following legacy files:

<script src="https://script.swiftcomplete.com/js/swiftcomplete.js"></script>
Copied

These older assets are deprecated and no longer maintained.

AreaLegacyNew (Swiftcomplete)
JavaScript scriptswiftcomplete.jsswiftlookup.js
CSSswiftcomplete.cssswiftlookup.css
API endpoint/v1/places/v1/swiftlookup/
Constructorswiftcompleteswiftcomplete
Class NamePlaceAutocompleteSwiftLookup
Eventsswiftcomplete:place:manualentry swiftcomplete:swiftlookup:manualentry
Eventsswiftcomplete:place:selectedswiftcomplete:swiftlookup:selected
Eventsswiftcomplete:userLocationswiftcomplete:swiftlookup:userLocation

📦 Notes for Developers

  • Existing integrations will continue to function, but all new integrations should adopt Swiftcomplete.
  • The Swiftcomplete library is more consistent with the latest postal datasets, brand styling, and performance standards.
  • Updated documentation and demos reflect this migration, ensuring an easier onboarding for developers.

Attributes

These are the configuration options passed into the Swiftcomplete component when initialising the autocomplete. Each parameter customises how the component behaves, from API keys and input fields to how results are displayed and filtered. Use these to tailor the experience to your platform.

Parameter NameValue (Example)TypeDescription
keyxxxxxStringAPI key for Swiftcomplete.
fieldinput-idStringThe HTML input element ID.
searchFor'what3words, address, place, road,transit'StringComma-separated types: address, what3words, place, transit, etc.Hierarchical. includes nested types like transit.airport.large (See the table below for more info)
emptyQueryMode'prompt' / 'results'StringWeb: 'prompt' or 'results'vv
scrollToFieldOnFocustrueBooleanIndicates if the field should be scrolled into view on focus.
populateLineCount5NumberNumber of address lines to populate. Max 8.
populateLineFormat[...]ArrayFormat for populating lines in the autocomplete field. lineFormat0=Company lineFormat1=SubBuilding,BuildingName lineFormat2=BuildingNumber SecondaryRoad, Road, PoBox lineFormat3=TertiaryLocality, SecondaryLocality lineFormat4=PrimaryLocality lineFormat5=POSTCODE lineFormat6=PrimaryCountry lineFormat7= what3words
hideOnEmptyResultsfalseBooleanHides the dropdown when results are empty.
requestDeviceLocationtrueBooleanRequests browser geolocation.
showControlAfterPermissionstrueBooleanShows control after permission is granted.
text 'w25eu' / 'London' / 'filled.count.soap'StringA full or partial search term such as a postcode, street, city or what3words.
promptText'Type your address...'StringDisplayed when search field is empty.
noResultsText'No results found, please try again!'StringDisplayed when search returns no results.
manualEntryText'Can't find your address? Click here to enter'StringDisplayed when user opts to manually enter address.

Available parameters for searchFor

LevelTypeDescription
First Level
what3wordsAll what3words addresses
addressAll traditional addresses
placePostcodes and all types of settlements (cities, towns, villages, counties, provinces, etc.)
roadAll types of roads
transitAll types of public transport
Second Level
place.areaPostcodes and counties, states, etc.
place.settlementCities, towns, villages, etc.
transit.airportAirports
transit.metroMetro and London Underground stops
transit.railwayRailway stations
transit.tramTram stops
Third Level
place.area.countyCounties
place.area.postcodePostcodes, Zip codes, etc
place.area.countryCountries
place.area.stateStates
place.area.provinceProvinces
place.area.territoryTerritories
place.settlement.largeLarge Cities
place.settlement.mediumCities &amp; towns
place.settlement.smallDistricts, villages &amp; hamlets
transit.airport.largeLarge international airports
transit.airport.mediumMedium regional airports
transit.metro.station.gblondondlrLondon DLR stations
transit.metro.station.gblondonundergroundLondon Underground stations
transit.tram.stop.gbcroydontramlinkLondon tram stops (Croydon Tramlink)
transit.tram.stop.gbedinburghtramsEdinburgh Tram stops
transit.tram.stop.gbmanchestermetrolinkManchester Metrolink tram stops
transit.tram.stop.gbnottinghamnetNottingham NET tram stops
transit.tram.stop.gbsheffieldsupertramSheffield Supertram tram stops
transit.tram.stop.gbwestmidlandsmetroWest Midlands Metro tram stops

Functions

These functions let you dynamically control the behaviour of the Swiftcomplete component after it has been initialised. You can change settings like maximum results, restrict searches to certain countries, or bias searches toward a specific location. Useful for custom logic and app flows.

Function NameExample UsageDescription
setMaxAutocompleteResults(amount)setMaxAutocompleteResults(5)Sets max results for general text searches (1–5).
setMaxContainerResults(amount)setMaxContainerResults(100)Sets max results when inside a container (1–100).
setSearchFor(types)setSearchFor('address,what3words')Restricts result types.
setCountries(code)setCountries('gb')Restrict search to countries (ISO 3166-1 alpha-2).
setMaxDistance(meters)setMaxDistance(3000)Restrict search radius in meters.
biasTowards(location)biasTowards('///filled.count.soap')Prioritise search near location or lat/lon.
setTextSearchOptions({...})setTextSearchOptions({...})Override search options like maxResults, countries, etc.
getDeviceLocation(true)getDeviceLocation(true)Requests geolocation, biases results.
getAddressAutocompleteCoverage()getAddressAutocompleteCoverage()['gb']Lists available countries for address autocomplete.
hasAddressAutocompleteCoverageForCountry('gb')trueChecks if a country supports autocomplete.
setReactFieldValue(el, value)setReactFieldValue(input, "new value")Updates React input state properly.

Custom Events

The component emits these events during the user’s interaction with the autocomplete. You can use them to trigger business logic, populate form fields, or track analytics. Mobile-specific equivalents are also supported where applicable.

Event NameTrigger SourceDescription
swiftcomplete:swiftlookup:selectedUser selects a resultReturns selected result with address lines, geometry, type, what3words address, etc.
swiftcomplete:swiftlookup:suggestionSuggestions fetchedReturns the list of current suggestions being displayed.
swiftcomplete:swiftlookup:userLocationDevice location usedReturns lat/lon of user location if geolocation is allowed.
swiftcomplete:swiftlookup:manualentryManual entry clickedTriggered when user opts to manually enter address.

Troubleshooting

Need help, or have any questions? Get in touch with our customer support team at support@swiftcomplete.com, and we’ll help you get started with the JavaScript integration for the Swiftcomplete API.

WebsiteUse 3 word addresses within an address searchJavaScriptSwiftComplete

Related tutorials