OpenLayers Geocoder Extension

by Jonatas Walker

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/css/ol.css">
<link rel="stylesheet" href="https://unpkg.com/ol-popup@4.0.0/src/ol-popup.css">
<link rel="stylesheet" href="https://unpkg.com/ol-geocoder/dist/ol-geocoder.min.css">
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script>
<script src="https://unpkg.com/ol-popup@4.0.0"></script>
<script src="https://unpkg.com/ol-geocoder"></script>
<div id="map" tabindex="0"></div>

CSS

html, body, #map {
    width:100%;
    height:100%;
    overflow:hidden;
}
body {
    font: 1em/1.5 BlinkMacSystemFont,-apple-system,"Segoe UI","Roboto","Oxygen","Ubuntu","Cantarell","Fira Sans","Droid Sans","Helvetica Neue","Helvetica","Arial",sans-serif;
    color: #222;
    font-weight: 400;
}

#map {
    position:absolute;
    z-index:1;
    top:0; bottom:0;
}
.ol-control button { 
    background-color: rgba(40, 40, 40, 0.8) !important;
}
.ol-control button:hover { 
    background-color: rgba(40, 40, 40, 1) !important;
}

JavaScript

var olview = new ol.View({ center: [0, 0], zoom: 2 }),
    baseLayer = new ol.layer.Tile({ source: new ol.source.OSM() }),
    map = new ol.Map({
      target: document.getElementById('map'),
      view: olview,
      layers: [baseLayer]
    });
    
// popup
var popup = new ol.Overlay.Popup();
map.addOverlay(popup);

//Instantiate with some options and add the Control
var geocoder = new Geocoder('nominatim', {
  provider: 'osm',
  lang: 'en',
  placeholder: 'Search for ...',
  limit: 5,
  debug: false,
  autoComplete: true,
  keepOpen: true
});
map.addControl(geocoder);
  
//Listen when an address is chosen
geocoder.on('addresschosen', function (evt) {
	console.info(evt);
  window.setTimeout(function () {
    popup.show(evt.coordinate, evt.address.formatted);
  }, 3000);
});