1.下载leaflet和leaflet.pm
leaflet 用于根据坐标自动绘制等操作,leaflet.pm可实现用户手动绘制。
leaflet.pm 参考网址:https://www.npmjs.com/package/leaflet.pm
leaflet 中文网址:https://leafletjs.cn/reference.html
2.引入在main.js中
import 'leaflet/dist/leaflet.css'
// 引入Leaflet对象 挂载到Vue上,便于全局使用,也可以单独页面中单独引用
import * as L from 'leaflet'
import 'leaflet.pm'
import 'leaflet.pm/dist/leaflet.pm.css'
Vue.config.productionTip = false;
Vue.L = Vue.prototype.$L = L
/* leaflet icon */
delete L.Icon.Default.prototype._getIconUrl
L.Icon.Default.mergeOptions({
iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
iconUrl: require('leaflet/dist/images/marker-icon.png'),
shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
})
代码示例
<template>
<div class="maps">
<button class="draw" @click="draws">绘制</button>
<button class="disdraw" @click="disdraw">关闭绘制</button>
<div id="map"></div>
</div>
</template>
<script>
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'
export default {
data () {
return {
map: '',
LatLngjosn: [],
rectangleGeoJson: '',
rectangleLayer: '',
pointMarkerList: []
}
},
mounted () {
this.initDate()
},
methods: {
addMarker () {
// 资源下图
this.removeMarkerLin()
// 点击地图绘制点位
this.map.once('click', e => {
// 点位上图,数组保存
this.pointMarkerList = []
const marker = L.marker([e.latlng.lat, e.latlng.lng], { id: this.videoSearchID }).addTo(this.mixMap)
this.pointMarkerList.push(marker)
})
},
removeMarkerLin () {
this.pointMarkerList.forEach(item => {
item.remove()
})
this.pointMarkerList = []
},
draws () {
// 设置多边形的颜色
const polygonOptions = {
templineStyle: {},
// the line from the last marker to the mouse cursor
hintlineStyle: {},
pathOptions: {
color: 'pink',
fillColor: 'pink'
}
}
this.map.pm.enableDraw('Polygon', polygonOptions)
this.rectangleLayer = this.map.pm.enableDraw('Polygon', {
snappable: true, // 启用捕捉到其他绘制图形的顶点
snapDistance: 20 // 顶点捕捉距离
})
},
disdraw () {
this.map.removeLayer(this.rectangleLayer)
this.draw = false
this.LatLngjosn = []
},
initDate () {
this.map = L.map('map', {
minZoom: 3,
maxZoom: 14,
center: [39.550339, 116.114129],
zoom: 12,
zoomControl: false,
attributionControl: false,
crs: L.CRS.EPSG3857
})
L.tileLayer(
'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
).addTo(this.map)
this.map.pm.setLang('zh')
this.map.on('pm:create', (e) => {
const shape = e.shape
// 多边形
if (shape === 'Polygon' || shape === 'Rectangle') {
// 处理绘制完成的逻辑
console.log(e)
console.log(e.layer._latlngs)
this.map.fitBounds(e.layer._latlngs) // 聚焦到选择的区域
this.LatLngjosn = e.layer._latlngs[0]
console.log(this.LatLngjosn)
this.draw = true
}
})
// 监听创建图形
this.map.on('pm:create', (e) => {
// 记录当前绘制的图形
this.rectangleGeoJson = e.layer.toGeoJSON()
this.rectangleLayer = e.layer
})
this.map.on('pm:remove', (e) => {
// 监听删除
console.log('删除了该区域')
})
}
}
}
</script>
<style>
#map {
width: 50%;
height: calc(50vh);
z-index: 1;
}
.maps{
width: 100vw;
height: 100vw;
}
</style>
