JavaScript Autocomplete for Addresses


Integration guide to find and validate addresses using JavaScript

JavaScript Integration Guide

This is a step-by-step guide to add an address autocomplete widget onto a website within minutes using lightweight open source JavaScript code. A range of address form combinations are covered to demonstrate how to simplify and speed up a checkout / registration form by auto-suggesting addresses while users type.

Address validation happens in real-time by calling Addy's address finder API to find addresses and ensuring address fields are complete and accurate with suburb, city and postcode.

Contact us if you need help and we will be happy to assist, free of charge.

Use the JavaScript Code Generator for fast and easy address autocomplete integration.

1,500 FREE completed address fields per month. Busy month? Just pay as you go for extras.

Examples

Autocomplete address form demo

This demo caters for a typical scenario where two address lines are available on a registration or checkout form.



The code sample is also available on GitHub and JSFiddle.

<!DOCTYPE html>
<html>
<head>
    <title>Autocomplete Address Lookup Example | Addy.co.nz</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="UTF-8">
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <link type="text/css" rel="stylesheet prefetch" href="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.min.css">
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 10pt;
        }
        .field {
            width: 300px;        
        }
        .label {
            width: 120px;
        }
    </style>
</head>
<body>
    <form>
        <table>
            <tr>
                <td class="label">Address Line 1</td>
                <td><input type="search" class="field" id="address_line_1" placeholder="Start typing an address.." auto-complete></td>
            </tr>
            <tr>
                <td>Address Line 2</td>
                <td><input type="text" class="field" id="address_line_2"></td>
            </tr>
            <tr>
                <td>Suburb</td>
                <td><input type="text" class="field" id="suburb"></td>
            </tr>
            <tr>
                <td>City</td>
                <td><input type="text" class="field" id="city"></td>
            </tr>
            <tr>
                <td>Postcode</td>
                <td><input type="text" class="field" id="postcode"></td>
            </tr>
        </table>
    </form>    
    <script type="text/javascript">
        // This is the callback function to initialise the address lookup
        function initAddy() {
            var addyComplete = new AddyComplete(document.getElementById("address_line_1"));
            addyComplete.fields = {
                address1: document.getElementById("address_line_1"),
                address2: document.getElementById("address_line_2"),
                suburb: document.getElementById("suburb"),
                city: document.getElementById("city"),
                postcode: document.getElementById("postcode")
            }
        }
    </script>
    <script src="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.min.js?key=demo-api-key&callback=initAddy&excludePostBox=false&maxItems=10" async defer></script>
</body>
</html>


Billing and shipping address demo

This demo caters for multiple address fields on a single page such as a billing and shipping address form. It is recommended to simplify the order page with an option to use the same billing and shipping address to improve checkout efficiency.

  • Use multiple address forms on a single page
  • Exclude PO Boxes and Private Bags (e.g. the shipping address)
  • Include Regions

Shipping Address


Billing Address


Sample code for a billing and shipping address capture form as shown below. View the code on GitHub.

<!DOCTYPE html>
<html>
<head>
    <title>Billing and Shipping Address Lookup | Addy.co.nz</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="UTF-8">
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <link type="text/css" rel="stylesheet prefetch" href="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.min.css">
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 10pt;
        }
        .field {
            width: 300px;        
        }
        .label {
            width: 120px;
        }
    </style>
</head>
<body>
    <form>
        <h2>Shipping Address</h2>
        <p><b>Physical NZ street addresses only.</b></p>
        <table>
            <tr>
                <td class="label">Address Line 1</td>
                <td><input type="text" class="field" id="shipping-address1" placeholder="Start typing an address.." auto-complete></td>
            </tr>
            <tr>
                <td>Address Line 2</td>
                <td><input type="text" class="field" id="shipping-address2"></td>
            </tr>
            <tr>
                <td>Suburb</td>
                <td><input type="text" class="field" id="shipping-suburb"></td>
            </tr>
            <tr>
                <td>City</td>
                <td><input type="text" class="field" id="shipping-city"></td>
            </tr>
            <tr>
                <td>Region</td>
                <td><input type="text" class="field" id="shipping-region"></td>
            </tr>
            <tr>
                <td>Postcode</td>
                <td><input type="text" class="field" id="shipping-postcode"></td>
            </tr>
        </table>
        <h2>Billing Address</h2>
        <p><b>Any NZ address; including PO Boxes or Private Bag numbers.</b></p>
        <p><label><input type="checkbox" id="billingChecked" checked onclick="toggleBilling()" /> Same as shipping</label></p>
        <table id="billing-table" style="display: none;">
            <tr>
                <td class="label">Address Line 1</td>
                <td><input type="text" class="field" id="billing-address1" placeholder="Start typing an address.." auto-complete></td>
            </tr>
            <tr>
                <td>Address Line 2</td>
                <td><input type="text" class="field" id="billing-address2"></td>
            </tr>
            <tr>
                <td>Suburb</td>
                <td><input type="text" class="field" id="billing-suburb"></td>
            </tr>
            <tr>
                <td>City</td>
                <td><input type="text" class="field" id="billing-city"></td>
            </tr>
            <tr>
                <td>Region</td>
                <td><input type="text" class="field" id="billing-region"></td>
            </tr>
            <tr>
                <td>Postcode</td>
                <td><input type="text" class="field" id="billing-postcode"></td>
            </tr>
        </table>
    </form>    
    <script type="text/javascript">
        // Show or hide the billing address
        function toggleBilling() {
            var table = document.getElementById("billing-table");
            table.style.display = table.style.display === "none" ? "block" : "none";
        }
        // This is the callback function to initialise the address lookup
        function initAddy() {
            // Shipping Address Lookup Setup
            var shippingAddy = new AddyComplete(document.getElementById("shipping-address1"));
            shippingAddy.fields = {
                address1: document.getElementById("shipping-address1"),
                address2: document.getElementById("shipping-address2"),
                suburb: document.getElementById("shipping-suburb"),
                city: document.getElementById("shipping-city"),
                region: document.getElementById("shipping-region"),
                postcode: document.getElementById("shipping-postcode")
            }
            shippingAddy.options.excludePostBox = true;
            // Billing address lookup setup
            var billingAddy = new AddyComplete(document.getElementById("billing-address1"));
            billingAddy.fields = {
                address1: document.getElementById("billing-address1"),
                address2: document.getElementById("billing-address2"),
                suburb: document.getElementById("billing-suburb"),
                city: document.getElementById("billing-city"),
                region: document.getElementById("billing-region"),
                postcode: document.getElementById("billing-postcode")
            }
        }
    </script>
    <script src="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.min.js?key=demo-api-key&callback=initAddy" async defer></script>
</body>
</html>


Single line address with a territory and region demo




The code sample is also available on GitHub and JSFiddle.

<!DOCTYPE html>
<html>
<head>
    <title>Address Lookup Single Line Form | Demo</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="UTF-8">
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <link type="text/css" rel="stylesheet prefetch" href="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.min.css">
    <style>
        .awesomplete {
            display: block !important;
        }
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 10pt;
        }
        .field {
            width: 300px;        
        }
        .label {
            width: 120px;
        }
    </style>
</head>
<body>
    <form>
        <table>
            <tr>
                <td class="label">Address</td>
                <td><input type="text" class="field" id="address" placeholder="Enter an address.." auto-complete></td>
            </tr>
            <tr>
                <td>Suburb</td>
                <td><input type="text" class="field" id="suburb"></td>
            </tr>
            <tr>
                <td>Town/City</td>
                <td><input type="text" class="field" id="city"></td>
            </tr>
            <tr>
                <td>Territory</td>
                <td><input type="text" class="field" id="territory"></td>
            </tr>
            <tr>
                <td>Region</td>
                <td>
                    <select id="region">
                        <option value="">Select a region ...</option>
                        <option value="301">Auckland</option>
                        <option value="303">Bay of Plenty</option>
                        <option value="312">Canterbury</option>
                        <option value="304">Gisborne</option>
                        <option value="305">Hawke's Bay</option>
                        <option value="307">Manawatu - Wanganui</option>
                        <option value="310">Marlborough</option>
                        <option value="315">Nelson</option>
                        <option value="300">Northland</option>
                        <option value="313">Otago</option>
                        <option value="314">Southland</option>
                        <option value="306">Taranaki</option>
                        <option value="309">Tasman</option>
                        <option value="302">Waikato</option>
                        <option value="308">Wellington</option>
                        <option value="311">West Coast</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>Postcode</td>
                <td><input type="text" class="field" id="postcode"></td>
            </tr>
        </table>
    </form>    
    <script type="text/javascript">
        // This is the callback function to initialise the address lookup script
        function initAddy() {
            var addyComplete = new AddyComplete(document.getElementById("address"));
            addyComplete.fields = {
                address1: document.getElementById("address"),
                suburb: document.getElementById("suburb"),
                city: document.getElementById("city"),
                postcode: document.getElementById("postcode"),
                territory: document.getElementById("territory"),
                region: document.getElementById("region")
            }
        }
    </script>
    <script src="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.js?key=demo-api-key&callback=initAddy" async defer></script>
</body>
</html>


Address lookup by country demo

In this demo, address suggestions will only show up when the selected country is New Zealand.




The code sample is also available on GitHub and JSFiddle.

<!DOCTYPE html>
<html>
<head>
    <title>Address Checker with Country Field | Addy.co.nz</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="UTF-8">
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <link type="text/css" rel="stylesheet prefetch" href="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.min.css">
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 10pt;
        }
        .field {
            width: 300px;        
        }
        .label {
            width: 120px;
        }
    </style>
</head>
<body>
    <form>
        <table>
            <tr>
                <td>Country</td>
                <td>
                    <select id="country" class="field" onchange="onCountryChange(this.value)">
                        <option value="AUS">Australia</option>
                        <option value="CAN">Canada</option>
                        <option value="NZL" selected="">New Zealand</option>
                        <option value="ZWE">Zimbabwe</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td class="label">Address Line 1</td>
                <td><input type="text" class="field" id="address_line_1" placeholder="Start typing an address.." auto-complete></td>
            </tr>
            <tr>
                <td>Address Line 2</td>
                <td><input type="text" class="field" id="address_line_2"></td>
            </tr>
            <tr>
                <td>Suburb</td>
                <td><input type="text" class="field" id="suburb"></td>
            </tr>
            <tr>
                <td>City/Town</td>
                <td><input type="text" class="field" id="city"></td>
            </tr>
            <tr>
                <td>Postcode</td>
                <td><input type="text" class="field" id="postcode"></td>
            </tr>
        </table>
    </form>    
    <script type="text/javascript">
        var addyComplete;
        // This is the callback function to initialise the address checker script
        function initAddy() {
            addyComplete = new AddyComplete(document.getElementById("address_line_1"));
            addyComplete.fields = {
                address1: document.getElementById("address_line_1"),
                address2: document.getElementById("address_line_2"),
                suburb: document.getElementById("suburb"),
                city: document.getElementById("city"),
                postcode: document.getElementById("postcode")
            }
            // Initialise the country value
            var country = document.getElementById("country");
            onCountryChange(country.options[country.selectedIndex].value);
        }
        function onCountryChange(value) {
            if (!addyComplete) return;
            // Enable/disable Addy based on the selected country
            if (value === "NZL") {
                addyComplete.enable();
            } else {
                addyComplete.disable();
            }
        }
    </script>
    <script src="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.js?key=demo-api-key&callback=initAddy" async defer></script>
</body>
</html>

Address Fields

Form Fields Configuration

This section describes how to assign address fields to a web form by using the JavaScript address lookup widget.

Only the "input" address field parameter as defined in the first constructor parameter is mandatory. Fields can be passed into the second constructor parameter or defined through the fields property.

<script type="text/javascript">
    // Address Autocomplete Instance
    var addyComplete = new AddyComplete(document.getElementById("address1"));
    
    // Map the fields to address controls
    addyComplete.fields = {
        address1: document.getElementById("address1"),
        address2: document.getElementById("address2"),
        ...
    }
</script>

The supported address fields are defined below:

Name Description JSON Mapping
address The display name of the address displayline
address1 Address line 1. Often used in combination with address2 address1
address2 Address line 2. Often used in combination with address1 address2
suburb The name of the suburb suburb
city The name of the city or mail town city
territory The name of the territory. See districts of New Zealand territory
region The name of the region. See regions of New Zealand region
postcode The postal code postcode
line1 Address Line 1 address1
line2 Address Line 2 address2
line3 Address Line 3 address3
line4 Address Line 4 address4

Populated Address Fields

This section describes the address fields that will be populated when an address is selected.

Examples:
  • Apartment / Building Address
    • Floor 23, 151 Queen Street, Auckland Central, Auckland 1010
  • Standard Address
    • 1 Fitzroy Road, Bluff Hill, Napier 4110
  • Rural Address
    • 115 Ngarongo Road, RD 13, Hawera 4673
  • PO Box Address
    • PO Box 1, Taupo, 335

Single Address Field

address suburb city region postcode
Floor 23, 151 Queen Street Auckland Central Auckland Auckland 1010
1 Fitzroy Road Bluff Hill Napier Hawke's Bay 4110
115 Ngarongo Road, RD 13 <Empty> Hawera Taranaki 4673
PO Box 1 <Empty> Taupo Waikato 3351

Two Address Fields

address 1 address 2 suburb city postcode
Floor 23 151 Queen Street Auckland Central Auckland 1010
1 Fitzroy Road <Empty> Bluff Hill Napier 4110
115 Ngarongo Road RD 13 <Empty> Hawera 4673
PO Box 1 <Empty> <Empty> Taupo 3351

Four Address Fields

line 1 line 2 line 3 line 4
Floor 23 151 Queen Street Auckland Central Auckland 1010
1 Fitzroy Road Bluff Hill Napier 4110 <Empty>
115 Ngarongo Road RD 13 Hawera 4673 <Empty>
PO Box 1 Taupo 3351 <Empty> <Empty>

Two Address Field - No Suburb Field

address 1 address 2 city postcode
Floor 23, 151 Queen Street Auckland Central Auckland 1010
1 Fitzroy Road Bluff Hill Napier 4110
115 Ngarongo Road RD 13 Hawera 4673
PO Box 1 <Empty> Taupo 3351

Configuration

URL Parameters

The example below shows the options that are available as URL parameters:

<script src="https://cdn.addy.co.nz/neatcomplete/2.1.0/addycomplete.min.js?key=demo-api-key&callback=initAddy&excludePostBox=false&excludeRural=false&excludeUndeliver=false&excludeSpelling=false&excludeWord=false&excludeIp=false&maxItems=10&loadcss=true&enableLocation=true&excludePostcodes=0622-1010&includePostcode=0622-1010&excludeRegion=1-2&includeRegion=3-4&excludeTerritory=1-2-3&includeTerritory=5-6-7&tag=sales&uniqueid=12345" async defer></script>

URL Parameter Default Value Description
key N/A Addy API Key
callback N/A An optional callback method name that should be executed when the addycomplete script has loaded
excludePostBox false Exclude PO Boxes and Private Bag addresses
excludeRural false Exclude rural addresses
excludeUndeliver false Exclude non-mail delivery addresses
excludeSpelling false Disable spelling correction from address matching
excludeWord false Disable extra word removal from address matching
excludeIp false Disable address sorting based on IP address proximity
excludePostcodes Exclude addresses within certain postcodes, defined in a dash separated list of postcodes
E.g. "1010-0622-7542". See the complete list of postcodes filters
includePostcode Only include addresses within certain postcodes, defined in a dash separated list of postcodes.
E.g. "1010-0622-7542". See the complete list of postcodes filters
excludeRegion Exclude addresses within certain regions, defined in a dash separated list of region codes
E.g. "1-2-6" for Northland, Auckland and Taranaki. See the complete list of region code filters
includeRegion Only include addresses within certain regions, defined in a dash separated list of region codes
E.g. "1-2-6" for Northland, Auckland and Taranaki. See the complete list of region code filters
excludeTerritory Exclude addresses within certain territories, defined in a dash separated list of territory codes
E.g. "22-14" for Kapiti Coast District and Hamilton City. See the complete list of territory code filters
includeTerritory Only include addresses within certain territories, defined in the dash separated list of territory codes
E.g. "22-14" for Kapiti Coast District and Hamilton City. See the complete list of territory code filters
tag Add a logging tag to every request
E.g. A department name such as "Sales"
uniqueid Add a unique Identifier to every request
E.g. An internal customer ID such as "12345"
maxItems 10 An optional parameter to specify the maximum number of address items to return
loadcss false Load the default addycomplete.min.css stylesheet
enableLocation false Enable reverse geocoding to return "Addresses near me"

JavaScript Configuration

URL parameters can be used as discussed above, which would apply the options to all of the address control instances on the page. The example below shows how to configure options in JavaScript for the addressComplete instance:


<script type="text/javascript">
    // Address lookup instance
    var addyComplete = new AddyComplete(document.getElementById("address_line_1"));
    
    // Configure address options
    addyComplete.setOption("exclude_postbox", true);
    addyComplete.setOption("max_results", 10);
                                    
    // Enable or disable reverse geocoding - ideal for custom mobile GPS client detection
    addyComplete.enableLocation();
    addyComplete.disableLocation();
                                    
    // exclude PO Box and Private Bag addresses
    addyComplete.setExcludePostbox(true);
    // exclude Non-Postal Delivery addresses (Postal Address File only)
    addyComplete.setExcludeUndeliverable(true);
    // exclude rural delivery addresses such as RD 3
    addyComplete.setExcludeRural(true);

    // disable spelling correction
    addyComplete.setExcludeSpelling(true);
    // disable extra word removal (e.g. Front Door, 16 Abc Road)
    addyComplete.setExcludeWordRemoval(true);
    // disable address sorting based on IP address proximity
    addyComplete.setExcludeIpOrder(true);

    // exclude postal codes (e.g. 10622 and 8024). 
    // See: https://www.addy.co.nz/faq-nz-postcode-list
    addyComplete.setExcludePostcodes('1062-8024');
    // only include addresses in specified postal codes (e.g. 1010,  9300 and 8302) 
    addyComplete.setIncludePostcodes('1010-9300-8302');

    // exclude addresses in region codes (e.g. 1, 2 and 3). 
    // See: https://www.addy.co.nz/faq-nz-regioncode-list
    addyComplete.setExcludeRegions('1-2-3');
    // only include addresses in specified region codes (e.g. 1, 2 and 3). 
    addyComplete.setIncludeRegions('1-2-3');

    // exclude addresses in territory/district codes (e.g. 1, 2 and 3). 
    // See: https://www.addy.co.nz/faq-nz-territorycode-list
    //addyComplete.setExcludeTerritories('5-6-7-8');
    // only include addresses in specified territory/district codes (e.g. 1, 2 and 3).
    addyComplete.setIncludeTerritories('5-6-7-8');

    // tag each request with a label for improved tracking
    addyComplete.setTag('sales');
    // tag each request with a unique identifier such as your internal customer's Id
    addyComplete.setUniqueId('1234');
</script>


Property Default Value Description
options.excludePostBox false An optional parameter to exclude PO Boxes and Private Bag numbers from the address results.
options.maxItems 10 Maximum number of address suggestions to display.

Advanced JavaScript Configuration

The example below shows how to register for the "address selected" event to enable full control over how to render and populate address fields on your website.

View the Address Details API documentation to learn more about the available address properties.


<script type="text/javascript">
    // Address lookup instance
    var addyComplete = new AddyComplete(document.getElementById("address"));
    
    // Register a function to receive the selected address object
    addyComplete.addressSelected = function(address) {
        console.log("Selected address object: ", address);
    }
</script>

Styling

CSS Branding Options

Use the CSS stylesheet elements below to control the theme, such as the colours and fonts, that will match your brand.


ul.nc_list {
    list-style: none;
    padding: 0;
    margin: 0;
    border: solid 1px #999;
    background: #ffffff;
    font-size: 15px;
    z-index: 1010;
}
ul.nc_list li.nc_item {
    cursor: pointer; 
    padding: 5px 5px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    border-bottom: 1px solid #cccccc;
}
ul.nc_list li.nc_item.nc_hover {
    background-color: #337ab7;
    color: white;
}
ul.nc_list li.nc_footer {
    font-size: 15px;
    color: #555;
    text-align: right;
    background: #eee;
    padding: 3px 5px;
    font-weight: bold;
}
li.nc_empty {
    padding: 5px 5px;
    border-bottom: 1px solid #cccccc;
}
.nc_highlight {
    font-weight: bold;
}


Styles and Content via JavaScript

Use the JavaScript below to modify the CSS class names or to change the content of the messages.


<script type="text/javascript">
    // Address lookup instance
    var addyComplete = new AddyComplete(document.getElementById("address_line_1"));
    
    // Configure styles and content
    addyComplete.setOption('empty_content', 'Address not found. Please verify the spelling.');
    addyComplete.setOption('footer_content', 'Search powered by addy.co.nz');
    addyComplete.setOption('list_class', 'nc_list');
    addyComplete.setOption('item_class', 'nc_item');
    addyComplete.setOption('hover_class', 'nc_hover');
    addyComplete.setOption('footer_class', 'nc_footer');
    addyComplete.setOption('highlight_class', 'nc_highlight');
</script>

Source Code

The code used in these examples, including third party dependencies (reqwest and neat-complete) are open source and available on GitHub.

There are no dependencies on heavyweight libraries such as jQuery and jQuery UI.