效果图:
一,插件安装
npm i leaflet --save // 我的版本^1.9.4
npm i leaflet.pm --save // 我的版本^2.2.0
附官网链接:
leaflet官网: https://leafletjs.com/index.html
leaflet.pm官网: https://www.npmjs.com/package/leaflet.pm?activeTab=readme
二,模块引入
因为我是单个页面需要所有就局部引入了,也可以放全局里面引入
<script>
import 'leaflet/dist/leaflet.css'
import 'leaflet/dist/leaflet'
import 'leaflet/dist/leaflet-src'
import 'leaflet/dist/leaflet-src.esm'
import * as L from 'leaflet'
import icon from 'leaflet/dist/images/marker-icon.png'
import iconShadow from 'leaflet/dist/images/marker-shadow.png'
import 'leaflet.pm'
import 'leaflet.pm/dist/leaflet.pm.css'
const DefaultIcon = L.icon({iconUrl: icon,shadowUrl: iconShadow,
})
L.Marker.prototype.options.icon = DefaultIcon
export default {data() {return {map: null,fillColor: '#2d75ff80',bounds: [[0, 0],[0, 0],], // 平面图大小}}
}
</script>
三,逻辑代码
<div id="imageMap"></div>......methods: {// 平面图初始化initMap() {this.map = L.map('imageMap', {minZoom: -3,zoom: 5,maxZoom: 4,zoomSnap: 0.1, // 缩放步长attributionControl: false, // 右下角图例控件zoomControl: true, // 缩放控件crs: L.CRS.Simple, // 坐标系center: [0, 0], // 中心点})this.map.pm.setLang('zh') // 控件提示设置中文this.map.pm.addControls({position: 'topleft', // 控件菜单位置drawPolygon: true, //绘制多边形drawMarker: true, //绘制标记点drawCircleMarker: true, //绘制圆形标记drawPolyline: true, //绘制线条drawRectangle: true, //绘制矩形drawCircle: true, //绘制圆圈editMode: true, //编辑多边形dragMode: true, //拖动多边形cutPolygon: true, //添加⼀个按钮以删除多边形⾥⾯的部分内容removalMode: true, //清除多边形})// 全局图层样式this.map.pm.setPathOptions({fillOpacity: 0.5,fillColor: this.fillColor,})},// 地图初始化initDate() {// 获取图片宽高,防止不同尺寸的图片回显在页面上有多余的留白问题let img = new Image()let url = require('../../public/home/bgc4.jpg')img.src = urlimg.onload = () => {let w = img.widthlet h = img.heightthis.bounds = [[0, 0],[h, w],]// 创建地图L.imageOverlay(url, this.bounds).addTo(this.map)// 设置地图图层区域this.map.fitBounds(this.bounds)}// 给地图绑定绘制、删除的事件this.map.on('pm:create', this.createClick)this.map.on('pm:remove', this.removeClick)// 禁止背景图拖拽,默认是可拖拽的this.map.dragging.disable()// 禁止双击缩放,默认是可双击缩放的this.map.doubleClickZoom.disable()// 禁止滚动缩放,默认是可滚动缩放的this.map.scrollWheelZoom.disable()},// 图层绘制完成createClick(e) {// console.log('图层绘制完成', e)// 设置图层样式e.layer.setStyle({fillOpacity: 0.5,fillColor: this.fillColor,// color:线段颜色// weight:线段宽度// opacity:线段透明度// dashArray:虚线间隔// fill:是否填充内部(true/false)// fillColor:内部填充颜色,如不设置,默认为color颜色// fillOpacity:内部填充透明度})// 给图层绑定点击、拖拽、编辑事件e.layer.on('pm:edit', this.editLayClick).on('click', this.layClick).on('pm:dragend', this.dragendLayClick)},// 图层删除removeClick(e) {// console.log('图层删除', e)},// 区域图层点击layClick(e) {// console.log('区域图层点击', e)},// 区域图层拖拽dragendLayClick(e) {// console.log('区域图层拖拽', e)},// 区域图层编辑editLayClick(e) {// console.log('图层编辑', e)},},mounted() {this.initMap()this.initDate()// 窗口缩放,地图自适应缩放window.onresize = () => {this.map.invalidateSize(true)this.map.fitBounds(this.bounds)}},
到这里就可以实现效果图所展示的功能了,下节详细说明各个模块及事件函数的功能.
所有示例代码已上传,点击前往获取
Done