leaflet使用L.KML.js插件上传本地kml文件到leaflet中

本文介绍如何在Web应用中实现用户上传本地KML文件并显示在地图上。使用了L.KML.js插件和Vue的naiveUI组件,通过读取文件为DataURL的方式加载KML数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

发现网上的案例都是加载项目assets内的kml文件,而实际的需求是:用户需要上传自己计算机上的kml文件,找了半天没找到案例,最后终于研究出来了,喜欢的点赞支持!

1.网上案例使用 L.KML.js插件代码如下(缺点是只能加载项目目录的kml):

<html>
    <head>
        <link rel="stylesheet" href="http://unpkg.com/leaflet@1.4.0/dist/leaflet.css" />
        <script src="http://unpkg.com/leaflet@1.4.0/dist/leaflet.js"></script>
        <script src="./L.KML.js"></script>
    </head>
    <body>
        <div style="width: 100vw; height: 100vh" id="map"></div>
        <script type="text/javascript">
            // Make basemap
            const map = new L.Map('map', { center: new L.LatLng(58.4, 43.0), zoom: 11 });
            const osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
            map.addLayer(osm);
            fetch('assets/aoi1.kml')
                .then(res => res.text())
                .then(kmltext => {
                  console.log(kmltext);
                    const parser = new DOMParser();
                    const kml = parser.parseFromString(kmltext, 'text/xml');
                    const track = new L.KML(kml);
                    map.addLayer(track);
                    // Adjust map to show the kml
                    const bounds = track.getBounds();
                    map.fitBounds(bounds);
                });
        </script>
    </body>
</html>

2.笔者实际开发中,用的是vue的naiveUI组件上传的kml文件(element UI和原生HTML5的input file原理一样),核心代码如下:

<template>
...
  <n-upload :on-change = "handleFileSelect" accept=".kml" :max="1">
   <span>上传kml</span>
 </n-upload>
...
</template>

<script>
...
handleFileSelect(evt){
  let file = evt.fileList[0].file; 
  const reader = new FileReader();
  reader.readAsDataURL(file)
  reader.onload = ()=>{
    fetch(reader.result)
    .then(res => res.text())
    .then(kmltext => {
      const parser = new DOMParser();
      const kml = parser.parseFromString(kmltext, 'text/xml');
      const track = new L.KML(kml);
      state.map.addLayer(track);
      // Adjust map to show the kml
      const bounds = track.getBounds();
      state.map.fitBounds(bounds);
     });
  }
  reader.onerror = e => console.log(e);
}
...
<script>

3.效果如下

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

q124467623

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值