最近因业务需求要在leaflet中展示kml文件,看了网上很多资料结合我们自己的情况,把leaflet加载kml文件的方法做了简单总结:
leaflet没有提供加载kml文件的方法,需要引入新的插件:https://github.com/windycom/leaflet-kml下载L.KML.js文件,在项目中引入(要放在leaflet后面)
注意:针对项目中的kml文件,文件要放在publish文件夹下,否则获取不到文件
初始化地图:
<template>
<div style="height: 100vh;position: relative;">
<div id="mapContainer" class="container"></div>
<div class="upload_file">
<input type="file" @change="handleFileChange" />
<button @click="handleShowFile(1)" style="display: block;margin-top: 10px;">加载本地kml</button>
<button @click="handleShowFile(2)" style="display: block;margin-top: 10px;">加载远程kml</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
map: null,
mapCenter: [29.154282, 119.793462], //地图中心
}
},
mounted() {
this.initMap()
},
methods: {
//初始化地图
initMap() {
this.map = L.map('mapContainer', {
crs: L.CRS.EPSG4326,
center: this.mapCenter,
maxZoom: 17,
minZoom: 5,
zoom: 10,
zoomControl: false,
attributionControl: false,
preferCanvas: true,
doubleClickZoom: false,
})
this.addSateLayer()
},
//添加卫星地图
addSateLayer() {
var wMap = L.supermap.tiandituTileLayer({
layerType: 'img',
key: '天地图key',
})
var lMap = L.supermap.tiandituTileLayer({
layerType: 'img',
isLabel: true,
key: '天地图key',
})
//添加影像图层
this.map.addLayer(wMap)
//添加标签图层
this.map.addLayer(lMap)
},
},
}
</script>
<style lang="less" scoped>
.container {
height: 100%;
width: 100%;
z-index: 400;
}
.upload_file {
z-index: 500;
position: absolute;
top: 50px;
left: 50px;
background-color: #fff;
padding: 10px;
border-radius: 10px;
}
</style>
初始化地图效果图:
一、本地kml和远程kml在地图中展示:
//加载kml文件
handleShowFile(type){
let that = this
let url = ''
if(type == 1){
url = 'assets/fly.kml'
}else{
url = 'kml文件远程链接'
}
fetch(url)
.then((o) => o.text())
.then((e) => {
const parser = new DOMParser()
const kml = parser.parseFromString(e, 'text/xml')
const track = new L.KML(kml)
that.map.addLayer(track)
//获取kml范围,并移动地图到该区域
const bounds = track.getBounds()
that.map.fitBounds(bounds)
})
}
效果如下:
前面的是项目中的kml文件,后面的是远程kml文件
二、上传本地kml并展示
//上传文件
handleFileChange(event) {
let that = this
let file = event.target.files[0]
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
let file_data = reader.result
fetch(file_data)
.then((o) => o.text())
.then((e) => {
const parser = new DOMParser()
const kml = parser.parseFromString(e, 'text/xml')
const track = new L.KML(kml)
that.map.addLayer(track)
//获取kml范围,并移动地图到该区域
const bounds = track.getBounds()
that.map.fitBounds(bounds)
})
}
},
展示在地图中的方法和上面的基本一致,只是增加了读取文件这一步
效果如下:
这几种展示方式基本上都是一样的,只是针对不同路径的文件有一些区别