发现网上的案例都是加载项目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.效果如下