openlayer加载本地kml的方法

openlayer官网上有kml加载显示的方法:
openlayer官网加载kml示例
只是其中url是相对前端服务器根目录路径:
openlayer加载本地kml的方法_第1张图片
然而开发过程中出现需要加载本地文件的需求,本来是想通过上传ftp曲线救国,但是考虑到现在很多浏览器放弃了对ftp的支持,故而放弃ftp思路,决定直接选择本地kml文件加载。
  由于直接使用file://协议会出现跨域问题,所以使用js的fileReader方式读取kml内容,然后使用openlayer的vectorsource 中kml format解析feature添加到数据源中,代码如下所示:

function addkmllayer(file) {
let newlayer;

var vectorSource2 = new VectorSource({
  format:new KML({
    extractStyles: false,
    // crossOrigin:"*"
  }),
  loader: function(extent, resolution, projection) {
     var reader = new FileReader();
    reader.onload = function() {
      let features=vectorSource2.getFormat().readFeatures(this.result
        ,
        {
          dataProjection: 'EPSG:4326',
          featureProjection: 'EPSG:3857'
        }
      );
      vectorSource2.addFeatures(features);

      let extent=newlayer.getSource().getExtent();
      map.getView().fit(extent);

      }
    reader.readAsText(file);
  },
);

newlayer = new VectorLayer({
  source:vectorSource2,
  style:new Style({
    fill:new Fill({
      color:[0xff,0xff,0x33,0.7]
    }),
    stroke:new Stroke({
      color:'black'
    })
  })
})
map.addLayer(
  newlayer
);
}

静态页面vue部件代码:






其中省略了map创建代码。
注意kml的epsg为4326,所以需要设置feature的坐标系:

   let features=vectorSource2.getFormat().readFeatures(this.result
        ,
        {
          dataProjection: 'EPSG:4326',
          featureProjection: 'EPSG:3857'
        }
      );
     

按照最后加载图层范围定位代码需要放到onload回调函数中,不然获取不到extent。

你可能感兴趣的:(GIS学习)