1.安装
npm install @mapbox/mapbox-gl-draw
2.引入
import mapboxgl from 'mapbox-gl';
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import StaticMode from '@mapbox/mapbox-gl-draw-static-mode';
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'
const modes = MapboxDraw.modes;
modes.static = StaticMode;
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.3.0/mapbox-gl-draw.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.3.0/mapbox-gl-draw.css' type='text/css' />
3.使用
<template>
<div class="panel-map">
<span class="title">停车场面域绘制</span>
<div
class="masking"
v-loading="mapRendering"
element-loading-text="地图渲染中"
/>
<base-map
ref="map"
:option="mapOption"
@mapReady="addControl"
>
</base-map>
</div>
</template>
<script>
//底层地图
import BaseMap from 'components/base-map-mapbox-ft';
//引入
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import StaticMode from '@mapbox/mapbox-gl-draw-static-mode';
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css';
import Api from '../api';
const modes = MapboxDraw.modes;
modes.static = StaticMode;
export default {
components: {
BaseMap
},
props: {
},
computed: {
},
data() {
return {
mapOption: {
zoom: 15,
center:['113.738','22.755']
},
mapRendering:false,
//添加绘制左上角绘制工具
draw: new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
},
modes: modes
}),
geojson: {
features: [],
type: "FeatureCollection"
},
//绘制类型分为添加面域add或者修改面域update
type:'add',
}
},
methods: {
//添加绘制组件
addControl() {
const map = this.$refs.map.getMap();
map.addControl(this.draw, 'top-left');
map.on('draw.create', this.updateArea);
map.on('draw.delete', this.updateArea);
map.on('draw.update', this.updateArea);
if ( this.actionType === 'update') {
this.initMapAndForm(map);
}
//左上侧工具按钮鼠标移入提示文字
const polygonButton = document.querySelector('.mapbox-gl-draw_polygon');
polygonButton.setAttribute('title', '绘制面域');
const trashButton = document.querySelector('.mapbox-gl-draw_trash');
trashButton.setAttribute('title', '删除面域');
//地图加载状态
this.mapRendering = false;
},
//将修改之前的面域绘制在地图上
initMapAndForm() {
//editData存储的是编辑之前的数据
if(!this.editData.geometry?.coordinates){
return
}
let arr = [];
this.editData.geometry.coordinates[0].forEach(coor => {
let poi = [coor[0]*1, coor[1]*1];
arr.push( poi );
});
this.geojson = {
type: "FeatureCollection",
features: [{
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [arr]
},
properties: {
fname:this.editData.fname,
}
}]
};
this.draw.add(this.geojson);
map.flyTo({
center: [this.editData.longitude*1,this.editData.latitude*1],
padding: 100,
zoom:15,
speed: 2,
curve: 1,
easing(t) {
return t
}
});
},
updateArea() {
//geojson存储的就是绘制面域的数据
this.geojson = this.draw.getAll();
}
}
}
</script>
<style lang="less" scoped>
.panel-map{
padding: 0 20px;
height: 180px;
.title{
display: inline-block;
margin-bottom: 10px;
}
}
</style>
4.效果
新增效果
编辑效果