Search code examples
javascriptopenlayersopenstreetmapgeocoding

Geocoding with osm map, javascript code and OpenLayers library


I want to Geocoding using OSM map, javascript code and OpenLayers library. .But I do not know what library I should use or what code to write.please guide me. Thanks I want to make changes to the code below to add Geocoding.

  <!DOCTYPE html>
    <html>
      <head>
        <title>Show OSM map</title>
        <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
        <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
        <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
        <style>
          html, body {
            height: 100%;
            width: 100%;
        padding: 0px;
        margin: 0px;
          } 
          .map {
            height: 90%;
            width: 100%;
          }
        </style>
        <script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
      </head>
      <body>
        <div id="map" class="map" "></div>
        <script>

          var map = new ol.Map({

            layers: [
              new ol.layer.Tile({
                source: new ol.source.OSM()
              })
            ],
            target: 'map',
            view: new ol.View({
              center: ol.proj.fromLonLat([51.39, 35.70]),
              zoom: 13
            })
          });
        </script>

    </script> 
      </body>
    </html>

Solution

  • If you're looking for controls to let the user search places on your map, have a look at this example with Nominatim or this with Photon API. Just create a control and add it to the map. Then do something when a place is selected (center the map):

    // Set the search control 
    var search = new ol.control.SearchNominatim ({
    // or: = new ol.control.SearchPhoton({
      lan: 'en',
      position: true    // Search, with priority to geo position
    });
    map.addControl (search);
    
    // Center map when destination is selected
    search.on('select', function(e) {
      map.getView().animate({
        center: e.coordinate,
        zoom: Math.max (map.getView().getZoom(),16)
    });
    

    If you want to geocode a bulk of addresses, look at API used by the example and their implementation in the lib.