OpenLayers: Autocomplete Geosearch Tutorial

Adding a Geosearch control to an OpenLayers map

OpenLayers is a powerful open source library to add maps to a website. Below is an example HTML page and map that includes an OpenCage Geosearch control to allow users to search for locations (cities, states, villages, etc) and then re-center the map on a selected location.

For details on how to control the map (set position, zoom, listen to events, add map markers, or set a different style) see the OpenLayers quick tutorial and reference documentation.

For details on how to configure the Geosearch control (number of results, language, or country filters) see the geosearch documentation. Changing the layout (fonts, colors) is explained on the algolia autocomplete theming reference guide.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!-- CSS files need to be in the head section -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@9.1.0/ol.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@opencage/ol-opencage-geosearch/ol-opencage-geosearch.css" />
  </head>
  <body>

    <!-- add a map element anywhere on the map -->
    <div id="map1" style="width:750px; height:500px;"></div>

    <!-- script can be either in the head section or anywhere below the map -->
    <script src="https://cdn.jsdelivr.net/npm/ol@9.1.0/dist/ol.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@opencage/geosearch-bundle"></script>
    <script src="https://cdn.jsdelivr.net/npm/@opencage/ol-opencage-geosearch/dist/ol-opencage-geosearch.js"></script>
    <script>
      // wait until everything is loaded
      document.addEventListener('DOMContentLoaded', () => {

        // create and initialize openlayers map object
        var map = new ol.Map({
          target: 'map1',
          layers: [
            new ol.layer.Tile({
              source: new ol.source.OSM()
            })
          ],
          view: new ol.View({
            center: ol.proj.fromLonLat([0, 40]),
            zoom: 0
          })
        });

        // geosearch options
        var options = {
          key: 'YOUR-GEOSEARCH-KEY',
          // you will need to become a customer to get a geosearch key
          // language: 'fr',
          // onSelect: (params) => { console.log('hello from onSelect', params) },
          position: 'topright'
        };

        // add geosearch to the map
        var controlGeosearch = new OpenCageGeosearchControl(options);
        map.addControl(controlGeosearch);
      });
    </script>
  </body>
</html>

OpenLayers map with an OpenCage Geosearch control

Other Geosearch options

We also have a Leaflet tutorial, and a codepen example showing how to add geosearch to a MapLibre map.