Geocoding on a Leaflet map Geocoding Tutorial

Please note: This tutorial is for our geocoding API, you may instead want our Leafletjs Geosearch Autosuggest tutorial

Install Leaflet Geocoding plugin

Add geocoding control to your webpage

To use the Leaflet plugin, load the plugin's CSS and JavaScript files:

<link rel="stylesheet" href="" />

<script src=""></script>

Then add the plugin's control to an L.Map instance:

var map ='map').setView([51.52255, -0.10249], 13);
var options = {
  key: 'YOUR-API-KEY',
  limit: 10,
  proximity: '51.52255, -0.10249' // favour results near here
var control = L.Control.openCageGeocoding(options).addTo(map);
L.tileLayer('{z}/{x}/{y}{r}.png?apikey=YOUR_THUNDERFOREST_API_KEY', {
  attribution: 'Data <a href="" target="_blank">OpenStreetMap</a> contributors, Map tiles &copy; <a href="">Thunderforest</a>',
  minZoom: 4,
  maxZoom: 18


Note: in this example we use map tiles from our friends at Thunderforest, but you can use any map provider.


By default, when a geocoding result is found, the control will center the map on it and place a marker at its location. This can be customized by overwriting the control's markGeocode function, to perform any action desired.

For example:

var control = L.Control.openCageGeocoding(options).addTo(map);

control.markGeocode = function(result) {
    var bbox = result.bbox;
This will add a polygon representing the result's boundingbox when a result is selected.


You can overwrite the following options, for example to translate.
var options = {
    key: 'YOUR-API-KEY',
    limit: 5                  // number of results to be displayed
    position: 'topright',
    placeholder: 'Search...', // the text in the empty search box
    errorMessage: 'Nothing found.',
    showResultIcons: false,
    collapsed: true,
    expand: 'click',
    addResultToMap: true,     // if a map marker should be added after the user clicks a result
    onResultClick: undefined, // callback with result as first parameter
    resultExtension: {        // additional attributes to add to result
        geohash: 'annotations.geohash',
        what3words: 'annotations.what3words',
        addressComponents: 'components'

var control = L.Control.openCageGeocoding(options).addTo(map);

See also

If you prefer to do your frontend development in React please check out react-leaflet-opencage.

Further Reading

Start your free trial

2,500 API requests per day.

No credit card required.