/ol-opencage-geocoding

Tutorial : how to use OpenCage data Geocoding API with OpenLayers

Primary LanguageJavaScriptMIT LicenseMIT

Tutorial : how to use OpenCage geocoding API with OpenLayers

Create the map

Here is bootstrap example from OpenLayers:

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@9.0.0/ol.min.css">
    <style>
        html,
        body,
        #map {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
        #map {
            position: absolute;
            z-index: 1;
            top: 0;
            bottom: 0;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/ol@9.0.0/dist/ol.js"></script>
    <title>Opencage Data with OpenLayers</title>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([7.7491, 46.0207]),
          zoom: 4
        })
      });
    </script>
  </body>
</html>

Add the geocoding widget to the OL map

To use the OL plugin, load the plugin's CSS and JavaScript files from jsDelivr:

<link href="https://cdn.jsdelivr.net/npm/ol-geocoder@latest/dist/ol-geocoder.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/ol-geocoder"></script>

Instantiate the geocoder with some options (ie. OpenCage API Key):

var geocoder = new Geocoder('nominatim', {
  provider: 'opencage', // <----- PROVIDER is opencage
  lang: 'en',
  key: 'YOUR-OPENCAGE-API-KEY',
  placeholder: 'Geocode with OpenCage...',
  limit: 5,
  debug: false,
  autoComplete: false,
  keepOpen: true,
});

and add the Control to the map

map.addControl(geocoder);

Add a nice popup plugin

<link rel="stylesheet" href="https://unpkg.com/ol-popup@5.1.0/src/ol-popup.css" type="text/css" />
<script src="https://cdn.jsdelivr.net/npm/ol-popup@5.1.0/dist/ol-popup.js"></script>

Display chosen address

Do something when an address is chosen:

geocoder.on('addresschosen', function (evt) {
  console.info(evt);
  popup.show(evt.coordinate, evt.address.formatted);
});

Resources

Licensing

Licensed under the MIT License

A copy of the license is available in the repository's LICENSE file.