Home / Docs / API Reference / City Search API

City Search API Documentation

Search for postcodes, cities and places with coordinates

The Swiftcomplete City Search API provides autocomplete, partial and full text matching for countries, places, postcodes & cities around the world. Streets, public transport and country-specific data (such as electoral districts) are available in selected countries.

For address validation with full postal address data, use our Address Autocomplete API.

Need any help? Get in touch and we'll guide you through the process of building an integration.

In this documentation:

Data CoverageAuthenticationIntegration OptionsJavaScript Autocomplete IntegrationAPI Integration

Data Coverage

Worldwide

Most major cities and towns, countries, states, provinces and administrative areas.

Great Britain (England, Scotland & Wales)

Postcodes, streets, cities, towns, villages, wards, districts, counties & ceremonial counties.

Transport coverage includes railway stations, tram stops, London Underground stations and DLR stations. Tram stops are available in Croydon, Edinburgh, Manchester, Nottingham, Sheffield and the West Midlands.

Authentication

Each request must be authenticated with a Places 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 Places API Key.

Integration Options

Once you've created a Places API Key, you can integrate Places search onto your website with the JavaScript Autocomplete Integration, or build an integration from scratch using the API.

JavaScript Autocomplete Integration

The JavaScript Swiftcomplete Places integration is a simple code snippet that can be included on your website to provide location autocomplete functionality.

Step 1: Include the code snippet

The first step is to copy and paste the code snippet into the <head> section of your HTML, before the closing </head> tag:

Code snippet
<script type="text/javascript">
    !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://script.swiftcomplete.com/js/swiftcomplete.js");
</script>
Step 2: Initialise Swiftcomplete Places

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 Places API key, and replace "INSERT_TEXT_FIELD_ID_HERE" with the ID of an existing textbox on your page.

The script initialises Swiftcomplete Places 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.

Initialise Swiftcomplete Places on page load
<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.PlaceAutoComplete({
                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:place:selected', function (e) {
                // Record
                console.log(e.detail.result.populatedRecord);

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

    window.addEventListener("load", initialiseSwiftcomplete, false);
</script>
Step 3: Test 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.

API Integration

Integrate the Swiftcomplete City Search API for general location and place search functionality.

Parameters
  • keystringrequired

    Places API Key.

  • textstring

    A full or partial search term, such as a postcode, street or city name. Text can be provided keystroke by keystroke for autocomplete suggestions as you type.

  • populateIndexinteger

    Used to obtain detailed information about a result in the response array. For example, to obtain full information for the first record, pass populatedIndex=0, or for the second, pass populatedIndex=1 and so on.

    The usual flow is to obtain a list of suggestions by making an API request without populatedIndex specified, and then allow the user to select a result in the list by passing populatedIndex in a second request.

    For integrations where a user isn't present to select a result (e.g. data cleansing or batch processing), simply pass populatedIndex=0 to automatically obtain detailed information about the most relevant result in the list.

  • biasTowardsstring

    WGS84 coordinates in the format "latitude,longitude".

    Prioritises results near your provided coordinates to increase relevance and reduce the number of keystrokes it takes to find a result.

    The API will prioritise results near your approximate location (determined by your IP address) if this parameter is not provided.

  • countriesstring

    A comma separated list of ISO 3166-1 alpha-2 country codes to restrict searching to certain countries (e.g. "ca,us" to restrict searching to Canada and the United States).

    The API will search globally if this parameter is not provided.

  • distanceUnitsstringdefault: metric

    Unit of measurement to display how far away the address if you provide coordinates to bias towards:

    • metric
    • imperial
  • maxResultsintegerdefault: 5

    Max number of results to return (up to 5).

  • searchForstring

    A comma separated list of result types to restrict the types of results that can be searched for.

    Types are hierarchical, so providing "transit" restricts searching to the transit category, "transit.airport" restricts searching for only airports and "transit.airport.large" restricts searching for the largest airports.

    Use the hierarchical types to filter results to only include exactly what you're looking for.

    First level:

    • 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 & towns
    • place.settlement.smallDistricts, villages & 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

    For example, pass "place.area.country,transit" to only search for country names and public transport.

    The API will search for all data types if searchFor is not provided.

Sample API Request
https://api.swiftcomplete.com/v1/places/?key=INSERT_KEY_HERE&countries=gb&biasTowards=52.929666,-1.275370&text=ng11eq&maxResults=1&populateIndex=0
API Response
  • primary.textstring

    A simplified summary of the main part of the address

  • primary.highlightsint[]

    Pairs of indexes into primary.text to indicate which characters have been matched. e.g. "[0,3,5,8]" indicates characters 0-3 and 5-8 have been matched.

  • secondary.textstring

    A simplified summary of the secondary description of the address

  • secondary.highlightsint[]

    The same as primary.highlights but for secondary.text

  • typestring

    A hierarchical type description of the address separated by full stops.

    See searchFor for a list of types.

  • recordDEPRECATED

    A text description of the result.

    record has been deprecated, in favour of populatedRecord which contains consistent, structured location information.

  • populatedRecordobject

    Structured location information, only present if populateIndex has been provided in the API request.

  • populatedRecord.linesstring[]

    An array of address lines representing a partial postal address. Note that the City Search API isn't suitable for postal address validation - use our Address Autocomplete API instead.

  • populatedRecord.labelstring

    Formatted partial postal address separated by newline characters. Note that the City Search API isn't suitable for postal address validation - use our Address Autocomplete API instead.

  • populatedRecord.dataobject

    A structured location object containing text and IDs for the result within standardised categories:

    • road
    • placeCity, town, village or district. Primary is the main place, with secondary and tertiary describing sub areas or districts (where relevant)
    • postalCodePostcodes / postal codes, ZIP codes
    • adminAdministrative and electoral areas, with IDs for cross referencing with government datasets
    • countryPrimary & secondary country (where relevant), with iso3166-2 code

    Depending on the country and the type of result (postcode, city etc.), not all categories will be populated with values.

    Standard information appears in the top level of a category, whereas country-specific information appears behind a country code. For example, outcodes are only relevant for the UK, and so appear in data.postalCode.gb, whereas full postal codes are relevant for many countries and so appear in the top level of the category at data.postalCode

  • geometry.centre.latfloat

    Latitude of the centre point of the address

  • geometry.centre.lonfloat

    Longitude of the centre point of the address

  • distance.unitsstring

    Unit of measurement to display how far away the address is from your provided coordinates

  • distance.measurementfloat

    Distance the address is from your provided coordinates, in units specified by distance.units

Sample API Response
[
    {
        "primary": {
            "text": "NG1 1EQ",
            "highlights": [
                0,
                2,
                4,
                6
            ]
        },
        "secondary": {
            "text": "Nottingham",
            "highlights": []
        },
        "type": "place.area.postcode",
        "isContainer": false,
        "geometry": {
            "centre": {
                "lat": 52.955574,
                "lon": -1.143074,
                "type": "postcode"
            }
        },
        "populatedRecord": {
            "lines": [
                "",
                "",
                "NOTTINGHAM",
                "NG1 1EQ",
                "United Kingdom"
            ],
            "label": "NOTTINGHAM\nNG1 1EQ\nUnited Kingdom",
            "data": {
                "postalCode": {
                    "text": "NG1 1EQ",
                    "isFullPostalCode": true,
                    "gb": {
                        "incode": {
                            "text": "1EQ"
                        },
                        "postcodeSector": {
                            "text": "1"
                        },
                        "postcodeUnit": {
                            "text": "EQ"
                        },
                        "outcode": {
                            "text": "NG1"
                        },
                        "postcodeArea": {
                            "text": "NG"
                        },
                        "postcodeDistrict": {
                            "text": "1"
                        }
                    }
                },
                "road": null,
                "country": {
                    "primary": {
                        "text": "United Kingdom",
                        "iso3166-2": "GB"
                    },
                    "secondary": {
                        "text": "England",
                        "iso3166-2": "GB-ENG"
                    }
                },
                "place": {
                    "primary": {
                        "text": "Nottingham"
                    },
                    "secondary": null,
                    "tertiary": null
                },
                "admin": {
                    "stateProvince": null,
                    "stateProvinceAbbreviation": null,
                    "gb": {
                        "county": {
                            "text": "Nottingham",
                            "code": "E06000018"
                        },
                        "ceremonialCounty": {
                            "text": "Nottinghamshire",
                            "code": null
                        },
                        "region": {
                            "text": "East Midlands",
                            "code": "E12000004"
                        },
                        "ward": {
                            "text": "Castle",
                            "code": "E05012277"
                        },
                        "district": {
                            "text": "Nottingham",
                            "code": "E06000018"
                        }
                    }
                }
            }
        },
        "countryCode": "gb"
    }
]