目录
一、创建dom节点
二、创建地图
三、添加底图(天地图),在地图创建完成后添加底图
本章主要讲述leaflet在vue中的使用:
leaflet 详情总目录:传送
一、创建dom节点
<div class="map" id="map_container"></div>
这里要注意,添加的节点必须设置宽高,否则不显示
二、创建地图
data() {return {map: null,//地图实例clickTimers: [],//存储区分点击地图双击和单击的定时器isShowUavBaseLayer: false, //是否显示卫星图层baseMapLayerGroup: null, //地图图层组tdtMapKey: '', //天地图key,需要到天地图申请}},methods: {initMap() {let that = thisthat.map = L.map('map_container', {crs: L.CRS.EPSG4326, //坐标系,在未知坐标系情况下,不要修改这里center: [29.4785541, 119.55847441], //地图中心maxNativeZoom: 16, //地图瓦片放大最大级别minNativeZoom: 5, //地图瓦片缩小最小级别maxZoom: 21, //地图放大最大级别minZoom: 5, //地图缩小最小级别zoom: 10, //地图当前级别attributionControl: false, //版本控件zoomControl: false, //地图缩放控件closePopupOnClick: true, //点击地图关闭popup弹窗trackResize: true, //地图根据浏览器更新boxZoom: true, //是否可以在按住shift拖地鼠标把地图缩放到指定的矩形区域doubleClickZoom: true, //是否双击放大地图dragging: true, //地图是否可以拖拽keyboard: true, //键盘是否可以操作地图keyboardPanDelta: 80, //键盘方向键按下时,地图平移像素scrollWheelZoom: true, //鼠标滚轮操作地图缩放wheelDebounceTime: 40, //鼠标滚轮触发限制,不得超过40毫秒一次wheelPxPerZoomLevel: 60, //鼠标滚动一次,地图滚动像素})//地图单击事件that.map.on('click', (e) => {//区分单击和双击,在单击添加延时,如果在300毫秒中触发了双击事件,则清除定时器,不触发单击事件let timer = window.setTimeout(() => {console.log(e.latlng, 'click')}, 300)that.clickTimers.push(timer)})//地图双击事件that.map.on('dblclick', (e) => {//判断定时器是否有数据,有则清除,只触发双击事件if (that.clickTimers.length > 0) {that.clickTimers.forEach((timer) => {window.clearTimeout(timer)})that.clickTimers = []}console.log(e.latlng, 'dblclick')})},},async mounted() {await this.$nextTick()this.initMap()},
创建的新地图是没有底图的,需要我们自己添加底图,根据需求添加不同的底图,我这里先以天地图为例,后期会把不同类型的底图添加方式统一写一下
三、添加底图(天地图),在地图创建完成后添加底图
//添加底图图层addSateLayer() {let layerType = this.isShowUavBaseLayer ? 'img' : 'vec'let labelType = this.isShowUavBaseLayer ? 'cia' : 'cva'if (!this.baseMapLayerGroup) {this.baseMapLayerGroup = new L.LayerGroup()this.baseMapLayerGroup.addTo(this.map)} else {this.baseMapLayerGroup.clearLayers()}var wMap = L.tileLayer(`https://t{s}.tianditu.gov.cn/DataServer?T=${layerType}_c&x={x}&y={y}&l={z}&tk=${this.tdtMapKey}`,{minZoom: 5,maxZoom: 21,maxNativeZoom: 17,minNativeZoom: 5,subdomains: [0, 1, 2, 3, 4, 5, 6, 7],zoomOffset: 1,tileSize: 256,})var lMap = L.tileLayer(`https://t{s}.tianditu.gov.cn/DataServer?T=${labelType}_c&x={x}&y={y}&l={z}&tk=${this.tdtMapKey}`,{subdomains: [0, 1, 2, 3, 4, 5, 6, 7],transparent: true,zIndex: 3,zoomOffset: 1,minZoom: 5,maxZoom: 21,tileSize: 256,})this.baseMapLayerGroup.addLayer(wMap)this.baseMapLayerGroup.addLayer(lMap)},//切换地图handleChangeBaseLayer() {this.isShowUavBaseLayer = !this.isShowUavBaseLayerthis.addSateLayer()},
效果如下:1.普通底图,2.卫星影像底图
注:这里用到天地图的key,需要到天地图官网申请