Geocoding with Leaflet

Adding an autocomplete search box to your Leaflet powered map is easy with Geocode Earth.

Here’s a complete HTML snippet that creates a full screen Leaflet map with search box:

<html>
  <head>
    <title>Geocode Earth Leaflet autocomplete demo</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css"
                           integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
                           crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"
            integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
            crossorigin=""></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet-geocoder-mapzen/1.9.4/leaflet-geocoder-mapzen.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-geocoder-mapzen/1.9.4/leaflet-geocoder-mapzen.js"></script>
    <style>
      html, body, #map {
        width: 100%; height: 100%;
        margin: 0; padding: 0; border: 0;
      }
    </style>
  </head>
<body>
  <div id="map"></div>

  <script>
    // create basic Leaflet map
    var map = L.map('map', {
      center:[42.35, -71.08],
      zoom: 3,
      minZoom:2,
      scrollWheelZoom: false,
      zoomControl: false
    });

    // add zoom control in topright corner
    L.control.zoom({ position:'topright' }).addTo(map);

    // Set Geocoder options
    var geocodingOptions = {
      url: 'https://api.geocode.earth/v1',
      expanded: true,
      attribution: '<a href="https://geocode.earth">Geocode Earth</a>, <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> and <a href="https://geocode.earth/guidelines">others</a>'
    };

    // Replace with your Geocode Earth API key
    L.control.geocoder('<YOUR API KEY>', geocodingOptions).addTo(map);

    // Add a raster tile layer
    L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', {
      attribution: 'Tiles by <a href="http://stamen.com">Stamen Design</a>',
      maxZoom: 17,
      minZoom: 1
    }).addTo(map);
  </script>
  </body>
</html>

Be sure to replace <YOUR API KEY> with your Geocode Earth API key.

See it in action #

For a working demo of what you’ll get, see our autocomplete demo.

Customizing #

The geocoder plugin can be customized in many ways, see the documentation on GitHub for more details.

Leaflet itself can also be extensively customized. See the Leaflet API Reference for everything Leaflet can do.