Search code examples
javascripthtmlopenlayerskml

How to upload and show kml file on map from user memory


I have a code showing maps and doing geocoding using a openlayers library.You can also display a kml file by dragging it on the map. Now I want the user to select this file from the device memory and insert it into the map. For example, use the search button and select the file to do this. Can the openlayers library be used? I could not find anything.How should I do this? please guide me. Thanks This is my code:

<!DOCTYPE html>
<html>
  <head>
    <title>KML</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/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>
<script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <div id="info">&nbsp;</div>
    <script>


      var raster = new ol.layer.Tile({
        source: new ol.source.BingMaps({
          imagerySet: 'Aerial',
          key: 'Ar3HbeAWJ2BNWw49Jnce_gbrbyqiPSBFuci9N4942gLNyBZgfzFPYn0d4QvpH06G'
        })
      });

      var vector = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'Data/earth.kml',
          format: new ol.format.KML()
        })
      });

      var map = new ol.Map({
        layers: [raster, vector],
        target: document.getElementById('map'),
        view: new ol.View({
          center: [58.3005,37.0554],
          projection: 'EPSG:4326',
          zoom: 13
        })
      });

      var displayFeatureInfo = function(pixel) {
        var features = [];
        map.forEachFeatureAtPixel(pixel, function(feature) {
          features.push(feature);
        });
        if (features.length > 0) {
          var info = [];
          var i, ii;
          for (i = 0, ii = features.length; i < ii; ++i) {
            info.push(features[i].get('name'));
          }
          document.getElementById('info').innerHTML = info.join(', ') || '(unknown)';
          map.getTarget().style.cursor = 'pointer';
        } else {
          document.getElementById('info').innerHTML = '&nbsp;';
          map.getTarget().style.cursor = '';
        }
      };

      map.on('pointermove', function(evt) {
        if (evt.dragging) {
          return;
        }
        var pixel = map.getEventPixel(evt.originalEvent);
        displayFeatureInfo(pixel);
      });

      map.on('click', function(evt) {
        displayFeatureInfo(evt.pixel);
      });
    </script>
  </body>
</html>

Solution

  • You can use an HTML Input and javascript FileReader

    <div id="map" class="map"></div>
    <input id="selectfile" type="file" accept=".kml" onchange="addKML()">
    <div id="info">&nbsp;</div>
    <script>
    
      function addKML() {
    
        var file = document.getElementById("selectfile").files[0];
        if (file) {
    
          var reader = new FileReader();
          reader.onload = function () {
    
            var vector = new ol.layer.Vector({
              source: new ol.source.Vector({
                url: reader.result,
                format: new ol.format.KML()
              })
            });
            map.addLayer(vector);
    
          }
          reader.readAsDataURL(file);
    
        }
    
      }