Documentation

What is Places?

Algolia Places is a geocoder providing a fast, distributed and easy way to use an address search autocomplete on your website. It is available as a Javascript autocomplete library, as a REST API and inside the JS, PHP, Swift and Android Algolia API clients.

Important: Algolia Places relies on OpenStreetMap data. Due to the sparseness of house level data in OSM, Places supports geocoding only up to the street level - house level precision is not guaranteed.

Getting started

To use Algolia Places, all you need is an <input> and some JavaScript code that will load
and use the places.js library.

CDN <script>

Our JavaScript library is available on the jsDelivr CDN.

1
<script src="https://cdn.jsdelivr.net/npm/places.js@1.15.0"></script>

Here's a small example using it:

1
2
3
4
5
6
7
8
9
10
<input type="search" id="address-input" placeholder="Where are we going?" />

<script src="https://cdn.jsdelivr.net/npm/places.js@1.15.0"></script>
<script>
  var placesAutocomplete = places({
    appId: 'YOUR_PLACES_APP_ID',
    apiKey: 'YOUR_PLACES_API_KEY',
    container: document.querySelector('#address-input')
  });
</script>

Note: You can access your Places credentials from the dashboard like any other Algolia application.
If you do not have a Places application, you can create one by signing up for free.

Important: We recommend using jsDelivr only for prototyping, not for production applications. Whenever possible, you should host your assets yourself or use a premium CDN service. jsDelivr is a free service and isn’t operated by Algolia, so we won’t be able to provide support if it fails.

Using npm

Algolia Places is also available on npm.

Install the module:

1
npm install places.js --save

Put an <input> in your html page:

1
<input type="search" id="address-input" placeholder="Where are we going?" />

Initialize the places.js library:

1
2
3
4
5
6
var places = require('places.js');
var placesAutocomplete = places({
  appId: 'YOUR_PLACES_APP_ID',
  apiKey: 'YOUR_PLACES_API_KEY',
  container: document.querySelector('#address-input')
});

Demo

As a result, you will get the Algolia Places autocompletion menu:

Usage

To turn any HTML <input /> into an address search bar make sure you include the places.js library and use the following initialization code:

1
2
3
4
5
6
7
const options = {
  appId: 'YOUR_PLACES_APP_ID',
  apiKey: 'YOUR_PLACES_API_KEY',
  container: '#my-input-DOM-selector',
  // ...
};
places(options);

Advanced example using all parameters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const fixedOptions = {
  appId: 'YOUR_PLACES_APP_ID',
  apiKey: 'YOUR_PLACES_API_KEY',
  container: document.querySelector('#demo'),
};

const reconfigurableOptions = {
  language: 'de', // Receives results in German
  countries: ['us', 'ru'], // Search in the United States of America and in the Russian Federation
  type: 'city', // Search only for cities names
  aroundLatLngViaIP: false // disable the extra search/boost around the source IP
};
const placesInstance = places(fixedOptions).configure(reconfigurableOptions);

// dynamically reconfigure options
placesInstance.configure({
  countries: ['us'] // only search in the United States, the rest of the settings are unchanged: we're still searching for cities in German.
})

Tip: Places application IDs always start by pl, which makes them recognizable at a glance.
If you do not have a Places application, you can create one by signing up for free.

Options

Here are the options you can pass to the places(options) function:

Static options

These options can only be set during the instantiation of the places application using

1
const placesInstance = places(options)
Static Option Description
container*

Type: HTMLInputElement

* Required

Determines the <input> that will be used for the Algolia Places autocompletion menu.

You just need to pass a reference to an Element. Obtained via document.querySelector for example.

Important: This parameter can only be set at instantiation.

appId

Type: string

The Places application ID to use.

Note: Create a Places app here.

Important: This parameter can only be set at instantiation.

apiKey

Type: string

The Places search API key to use.

Important: This parameter can only be set at instantiation.

templates

Type: Object

Change the templates used in place.js.

Available templates:

  • value
  • suggestion

Each template is a function that will receive a suggestion object and must return a string.

value must return a plain string as it's used to fill the input.value. suggestion should return an HTML string to be displayed in the dropdown.

style

Type: boolean

Control whether the default styles should be used.

Default: Styles are enabled.

Important: This parameter can only be set at instantiation.

Reconfigurable options

These options can be set during the instantiation of the places application using

1
const placesInstance = places(options)

or at any time using

1
placesInstance.configure(options)
Reconfigurable option Description
type

Type: string

Restrict the search results to a specific type.

Available types:

  • city
  • country
  • address
  • busStop
  • trainStation
  • townhall
  • airport

Default: Search in all types.

Note: If you restrict the search to city or airport, you probably want to disable the aroundLatLngViaIP option as well. This will make sure you don't get only nearby results.

language

Type: string

Change the default language of the results. You can pass two letters language codes (ISO 639-1).

Default: Current user language obtained via navigator.language in the two letter form. Example: en when navigator.language is en_US.

countries

Type: string[]

Change the countries to search in. You must pass an array of two letters country codes (ISO 639-1).

Default: Search on the whole planet.

aroundLatLng

Type: string

Force to first search around a specific latitude longitude. The option value must be provided as a string: latitude,longitude like 12.232,23.1.

The default is to search around the location of the user determined via his IP address (geoip).

aroundLatLngViaIP

Type: boolean

Whether or not to first search around the geolocation of the user found via his IP address. This is true by default.

aroundRadius

Type: number

Radius in meters to search around the latitude longitude. Otherwise a default radius is automatically computed given the area density.

insideBoundingBox

Type: string

Filters the results inside the area defined by the two extreme points of a rectangle. See guide.

Format: topRightLat, topRightLng, bottomLeftLat, bottomLeftLng

Example: "60, 16, 40, -4"

insidePolygon

Type: string

Filters the results inside the area defined by a shape. See guide.

Format: p1Lat, p1Lng, p2Lat, p2Lng, p3Lat, p3Lng...

getRankingInfo

Type: boolean

Controls whether the _rankingInfo object should be included in the hits. This defaults to false.

The _rankingInfo object for a Places query is slightly different from a regular Algolia query and you can read up more about the difference and how to leverage them in our guide.

useDeviceLocation

Type: boolean

Ask and use the device location.

computeQueryParams

Type: object

Allows you to override computed query parameters sent to the Algolia Places REST API.

Advanced static options

These are very advanced options that can be only set during the instantiation of the places application using

1
const placesInstance = places(options)

These options should not be considered for regular use cases.

Advanced static option Description
clientOptions

Type: object

Algolia JavaScript API client options.

Note: This is an advanced option.

autocompleteOptions

Type: object

autocomplete.js options to configure the underlying autocomplete.js instance.

Note: This is an advanced option.

Events

The Algolia Places autocomplete exposes some events that you can register to:

1
2
3
4
5
6
7
var placesAutocomplete = places({
  appId: 'YOUR_PLACES_APP_ID',
  apiKey: 'YOUR_PLACES_API_KEY',
  container: document.querySelector('#demo')
});

placesAutocomplete.on('change', e => console.log(e.suggestion));
Event Description
change

Event data:

  • query
    Type: string
  • rawAnswer
    Type: object
  • suggestion
    Type: suggestion
  • suggestionIndex
    Type: number

Fired when suggestion selected in the dropdown or hint was validated.

You can use this event to then populate another form, see the example.

suggestions

Event data:

  • rawAnswer
    Type: object
  • query
    Type: string
  • suggestions
    Type: Array<suggestion>

Fired when dropdown receives suggestions. You will receive the array of suggestions that are displayed.

You will also receive this event when no places were found.

You can use this event to display the suggestions on a map, see the map example.

cursorchanged

Event data:

  • rawAnswer
    Type: object
  • query
    Type: string
  • suggestion
    Type: suggestion
  • suggestionIndex
    Type: number

Fired when arrows keys are used to navigate suggestions.

You can use this event to highlight markers on a map, see the map example.

clear

Event data: undefined

Fired when the input is cleared. This event doesn't return anything, as the value of the query is then '' and no suggestion is displayed nor selected.

You can use this event when used with a map to reset the pins and the default center. See this behaviour live on the map example.

limit

Event data:

  • message
    Type: string

Fired when you reached your current rate limit.

error

Event data:

  • message
    Type: string

Fired when we could not make the request to Algolia Places servers for any reason but reaching your rate limit.

Methods

We provide some methods to help you interact with the places.js autocomplete instance.
If you have a good use case for a new method, open a new issue about it.

Name Description
open

Returns: undefined

Usage: placesAutocomplete.open()

Opens the dropdown menu. The menu will be visible if it has content to show.

close

Returns: undefined

Usage: placesAutocomplete.close()

Closes the dropdown menu.

getVal

Returns: string

Usage: placesAutocomplete.getVal()

Get the current input value.

setVal

Returns: undefined

Usage: placesAutocomplete.setVal()

Set the current input value. This will not open the menu. You will need to call .open()

destroy

Returns: undefined

Usage: placesAutocomplete.destroy()

Removes the places autocomplete instance, switch the input back to it's original behavior.

Suggestions

All of the events will send suggestion objects with those properties:

Property Description
type

Type: string

Type of the current suggestion, possible values: country, city, address, busStop, trainStation, townhall, airport.

name

Type: string

Display name of the place found.

Examples:

  • Paris
  • 589 Howard Street San Francisco
city

Type: string

City name.

country

Type: string

Country name.

countryCode

Type: string

Two letters country code (ISO 639-1).

administrative

Type: string

Administrative region depending on the country.

Examples:

  • Pays de la Loire
  • Texas
  • Catalunya
county

Type: string

County level administrative region depending on the country.

Examples:

  • Corrèze
  • Clark County
suburb

Type: string

Suburb name.

Examples:

  • Angelino heights
  • Harbor City
latlng

Type: Object

Latitude and longitude of the place found. Shape: {lat: 48.797885, lng: 2.337034}.

postcode

Type: string

The best matching postcode (or ZIP Code) of the place found.

Examples:

  • 94104
  • 75009
postcodes

Type: array

The list of all postcode (or ZIP Code) of the place found.

Examples:

  • ["94102", "94103", "94104", ... ]
  • ["75008", "75009"]
value

Type: string

Full display name of the place found. It's the value displayed in the input.

Examples:

  • Paris Île-de-France, France
  • 589 Howard Street San Francisco, California, United States of America
highlight

Type: object

Given the query, contains the highlighted values of the following attributes:

  • name
  • suburb
  • city
  • postcode
  • county
  • administrative
  • country

Example:

1
2
3
4
5
6
7
// query was `par`
console.log(suggestion.highlight);
// {
//   name: '<em>Par</em>is',
//   administrative: 'Île-de-France',
//   country: 'France'
// }

Integrations

On top of the regular places component, the places.js library offers additional integrations with autocomplete.js and InstantSearch.js.

autocomplete.js

The places.js library is leveraging Algolia's autocomplete.js library.

To be able to combine your own data along with showing results of Algolia Places, we provide an autocomplete.js dataset:

1
<script src="https://cdn.jsdelivr.net/npm/places.js@1.15.0/dist/cdn/placesAutocompleteDataset.min.js"></script>

The autocomplete.js dataset is exported as placesAutocompleteDataset in the window, also available with npm using:

1
import placesAutocompleteDataset from 'places.js/placesAutocompleteDataset';

All the places.js options are available and can be passed to the placesAutocompleteDataset function. The places.js CSS file is automatically loaded so that the rendering of suggestions is already the one you will expect.

You will need an Algolia account to be able to search into your own data. See the autocomplete.js dataset example.

InstantSearch.js

If you're already using instantsearch.js, you can use Algolia Places out of the box. This
widget will do a search of places using Algolia Places and when an address is selected, it
will update the geolocation point of the instantsearch.js search.

You can include it using a link tag:

1
<script src="https://cdn.jsdelivr.net/npm/places.js@1.15.0/dist/cdn/placesInstantsearchWidget.min.js"></script>

The widget is exported as placesInstantsearchWidget in the window. It is also available with
npm using:

1
import widget from 'places.js/placesInstantsearchWidget';

The widget accept the same options as places.js. Because it is an instantsearch.js that
will have an impact on the instantsearch search, it contains other options:

Option Description
defaultPosition

Type: number[]

Sets the default position around which the instantsearch search is done, when no element is selected in the places widget. This position is an array of two numbers, representing the latitude and the longitude.

Security

The default way of using Places is to pass your Places application ID and API Key to the Places library.
However, since the Places library is user-facing, this means that your credentials can be exposed.

It is therefore recommended to put in place some extra limitations in order to prevent any abuse of your API Key. Algolia offers two solutions to restrict the usage of your API Keys, which can be combined together:

Note: This section will not go in extreme details about the concepts that are presented as they are explained in great lengths in the official Algolia documentation.

Restricted API Keys

In Places like in any other Algolia application, you can set up authorizations and restrictions with a great level of precision when creating API keys. It’s common to combine these rules to make it very hard to use a public API key to crawl your data.

You can read more about creating restricted API Keys in the official Algolia documentation.

For instance, for Places, it is common practice to have a restricted API Key with the following restrictions:

Designing such an API Key will protect your API Key from being used by other website, while partially mitigating attacks from other tools without having to implement an advanced security system or having to route your calls through your backend for validation, which would increase the latency of each query.

Secured API Keys

If you want to have strong control on who accesses Places with your API Key, you can use secured API Keys. This will require a back-end implementation of the secured API Key generation.

For instance, for Places, you can create short-lived API Keys for every single user based on your own metrics, using secured API Keys.

There is a great tutorial on how to use secured API Keys in the official documentation of Algolia.

Styling

Algolia Places can fit existing designs. By default only the dropdown has a default light style.

See our styling example.

HTML structure

The overall html structure looks like this:

1
2
3
4
5
<span class="algolia-places">
  <input class="ap-input" />
  <button type="button" class="ap-input-icon ap-icon-clear"><svg></svg></button>
  <button type="button" class="ap-input-icon ap-icon-pin"><svg></svg></button>
</span>

Then the dropdown html structure looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
<span class="ap-dropdown-menu">
  <div>
    <span class="ap-suggestions">
      <div class="ap-suggestion">
        <span class="ap-suggestion-icon"><svg></svg></span>
        <span class="ap-name"></span>
        <span class="ap-address"></span>
      </div>
      <!-- Other suggestions -->
    </span>
  </div>
</span>

CSS classes

Here's a visual explanation of the different CSS classes:

preview-places
preview-places
CSS Class Description
.ap-input

This class is the one use by the main places input

.ap-icon-pin

This is the class attached to the pin icon, which is visible when the input is on it's normal state

.ap-icon-clear

This is the class attached to the clear icon, which is visible when the input is filled, clicking it will empty the input

.ap-dropdown-menu

This class is the one that is on the whole suggestions wrapper

.ap-suggestion

The .ap-suggestion class is the class of each dropdown suggestions

.ap-cursor

The .ap-cursor class is added to .ap-suggestion when the suggestion is hovered

.ap-suggestion-icon

The .ap-suggestion-icon is the class that is used on the left icon of each suggestions

.ap-name

The .ap-name class is the one used on the name of the place

.ap-address

The .ap-address class is the one used on the address of the place

<em>

The <em> tag in the .ap-suggestion is the tag that is used to make an highlight on each names

Here's a default empty CSS file you can copy paste to tune the default styling:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* Main input wrapper */
.algolia-places {}

/* The algolia-places input */
.ap-input, .ap-hint {}

/* The style of the svg icons when the input is on hover */
.ap-input:hover ~ .ap-input-icon svg,
.ap-input:focus ~ .ap-input-icon svg,
.ap-input-icon:hover svg {}

/* The dropdown style */
.ap-dropdown-menu {}

/* The suggestions style */
.ap-suggestion {}

/* The highlighted names style */
.ap-suggestion em {}

/* The addresses style */
.ap-address {}

/* The icons of each suggestions ( can be a building or a pin ) */
.ap-suggestion-icon {}

/* The style of the svg inside the .ap-suggestion-icon */
.ap-suggestion-icon svg {}

/* The icons inside the input ( can be a pin or a cross ) */
.ap-input-icon {}

/* The style of the svg inside the .ap-input-icon */
.ap-input-icon svg {}

/* .a-cursor is the class a suggestion go on hover */
.ap-cursor {}

/* The style of the svg icon, when the .ap-suggestion is on hover */
.ap-cursor .ap-suggestion-icon svg {}

/* The styles of the Algolia Places input footer */
.ap-footer {}

/* The styles of the Algolia Places input footer links */
.ap-footer a {}

/* The styles of the Algolia Places input footer svg icons */
.ap-footer a svg {}

/* The styles of the Algolia Places input footer on hover */
.ap-footer:hover {}

Disable default style

By default we insert some styling into your page. You can disable all the Algolia Places styling by passing the style: false option.

Once you do so, all CSS classes will be prefixed with ap-nostyle and no styling will be applied anymore.

Pin and clear icons will still be shown and working, without being styled.

Licenses & Policies

You can display Algolia Places results on any map provider.

In accordance with our terms of use, you are required to comply with our Acceptable Use Policy.

If your application uses places.js library, then the Algolia logo must be included and not altered. If your application uses the Places API directly or any other API client, you must show a "Search by Algolia" logo next to the data. You can find the logo in SVG format here.

The places.js is licensed under MIT.

Address data is produced regularly processing different datasets such as:

© OpenStreetMap using the Planet.osm dataset under the Open Database License (ODbL) v1.0.

© GeoNames database under the Creative Commons Attribution 4.0 License.

BAN dataset for France under ODbL v1.0.

IGN Admin Express dataset under the Open License 1.0.

Browser support

Algolia Places comes with native support for all latest stable versions of current major browsers: Chrome, Firefox, Edge, Opera and Safari. Previous versions of those modern browsers should also work. But since those are auto-updating browsers, we do not guarantee it.

Algolia Places also works natively on Internet Explorer 11 and 10.

To support Internet Explorer 9, you need to include a polyfill for Element.classList. To do so, you can use the Polyfill.io service.

Examples

Have a look at our examples page.