<template> <div id="map" ref="map" class="baseMap"> <slot/> </div> </template> <script> import L from 'leaflet' import 'leaflet/dist/leaflet.css' export default { name: 'LeafletMap', props: { layers:{ type: Array, required: true }, // 图层地址列表 zoom:{ type: Number, default: 15 }, // 缩放 zooms:{ type: Array, default:()=>{ return [14,20] } }, // 缩放范围 center:{ type: Array, default:()=>{ return [113.497393,22.289656] } }, // 地图中心 crs:{ type: String, default: '3857' } }, data () { return { map: null, baseLayers: [], } }, mounted () { this.initMap() }, watch: { layers:{ handler(val){ console.log(val) this.clearLayers() this.addLayers() }, deep: true }, zoom(){ }, center(){ } }, methods: { // 初始化地图 initMap () { const {zooms, zoom, center, crs} = this const map = L.map(this.$refs.map, { minZoom: zooms[0], maxZoom: zooms[1], center: center, zoom: zoom, zoomControl: false, doubleClickZoom: false, // 禁用双击放大 attributionControl: false, crs: crs=='3857'?L.CRS.EPSG3857:L.CRS.EPSG4326 }) map.doubleClickZoom.disable() this.map = map // data上需要挂载 this.$emit('onload', map) // 加载图层 this.addLayers() }, // 添加图层 addLayers () { console.log('addLayers') const {map, layers} = this layers.forEach(layerInfo=>{ if(layerInfo.show){ const options = {} if(layerInfo.zooms){ options.minZoom = layerInfo.zooms[0] options.maxZoom = layerInfo.zooms[1] }// 缩放情况 const layer = L.tileLayer(layerInfo.url, options) this.baseLayers.push({name: layerInfo.name, layer: layer.addTo(map)}) } }) }, // 清除所有图层 clearLayers(){ const {map} = this this.baseLayers.forEach(layer=>{ map.removeLayer(layer) }) this.baseLayers = [] }, // 清除指定图层 clearLayer(){ const {map, layers, baseLayers} = this layers.forEach(layerInfo=>{ // 如果需要显示 if(layerInfo.show){ // 判断当前图层是否显示 const findResults = baseLayers.filter(item=>{item.name==layerInfo.name}) if(findResults.length==0){ // 未显示则添加显示并放入baseLayers const options = {} if(layerInfo.zooms){ options.minZoom = layerInfo.zooms[0] options.maxZoom = layerInfo.zooms[1] }// 缩放情况 const layer = L.tileLayer(layerInfo.url, options) this.baseLayers.push({name: layerInfo.name, layer: layer.addTo(map)}) } }else{ // 不需要显示, 先判断当前图层是否显示,若已显示则移除 for(let i=0;i<baseLayers.length;i++){ if(baseLayers[i].name==layerInfo.name){ map.removeLayer(baseLayers[i].layer) this.baseLayers.splice(i,1) } } } }) } } } </script> <style rel="stylesheet/scss" lang="scss" scoped> .baseMap { height: 100%; width: 100%; /*border: 1px solid #DCDCDC;*/ /*border-radius: 4px;*/ } </style>