首页 > 解决方案 > 如何在通过 html 输入表单上传传单地图时立即在传单地图上加载 geojson?

问题描述

我想构建允许客户端从 html 表单上传 geojson 文件的系统,这些数据将显示在传单地图上。当我尝试这样做时,它显示错误代码 405。我想提交包含geojson 文件的表单并使用leaflet-omnivore 插件加载此文件。我的 html 文件为,

<section class="addVectorLayer">
        <form action="" method="POST" class="vector">
            Click to add your vector layer. It support Json, Geojson, csv, gpx and kml formats.
            <input type="file" name="files" id="input_files">
        </form>
</section>

我的js文件在这里,

geojson.onlode = function() {
    geojson.readAsDataURL(document.getElementById('input_files').files[0]);
    };
    omnivore.geojson(geojson.result).addTo(map);

请注意,我不想要异步调用。

标签: javascriptleafletgeojson

解决方案


我添加了一些基于这个插件的代码。这对我有用。更好的方法受到高度评价。

var fileInput = document.getElementById('input_files');

   fileInput.addEventListener('change', function (event) {
      var file = fileInput.files[0],
         fr = new FileReader();
      fileInput.value = ''; // Clear the input.
      extention = file.name.split('.')[1]
      if (extention === 'geojson') {
         fr.onload = function () {
            var layer = omnivore.geojson(fr.result).addTo(map);
            map.fitBounds(layer.getBounds());
         };
         fr.readAsDataURL(file);
      }
   });


推荐阅读