Skip to content

Commit 8da31b4

Browse files
committed
增加顶点编辑器
1 parent d0f9d30 commit 8da31b4

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import MapboxDraw from "@mapbox/mapbox-gl-draw";
2+
import { IMap, TIdentityGeoJSONFeature } from '../types';
3+
4+
export class VertexEditor {
5+
private editor: MapboxDraw;
6+
7+
/**
8+
*
9+
*/
10+
constructor(private map: IMap) {
11+
// 创建编辑器
12+
this.editor = new MapboxDraw({
13+
controls: {
14+
trash: true
15+
},
16+
displayControlsDefault: false
17+
});
18+
this.editor.onAdd(map as any);
19+
// 禁止图形平移
20+
const onDrag = MapboxDraw.modes.direct_select.onDrag;
21+
MapboxDraw.modes.direct_select.onDrag = function (this, state, e) {
22+
if (state.selectedCoordPaths.length > 0)
23+
onDrag?.call(this, state, e);
24+
};
25+
// 禁止删除图形
26+
const directSelectOnTrash = MapboxDraw.modes.direct_select.onTrash;
27+
MapboxDraw.modes.direct_select.onTrash = function (this, state) {
28+
const featureType = state.feature.type;
29+
const coordinates = state.feature.coordinates;
30+
if ((featureType === 'Polygon' && coordinates[0].length > 3) ||
31+
(featureType === 'LineString' && coordinates.length > 2)
32+
) {
33+
directSelectOnTrash?.call(this, state);
34+
}
35+
}
36+
MapboxDraw.modes.simple_select.onTrash = function (this, _) { }
37+
}
38+
39+
setFeature(feature: TIdentityGeoJSONFeature, onChange: (feature: TIdentityGeoJSONFeature) => void) {
40+
const fId = feature.properties.id;
41+
feature.id = fId;
42+
const geometryCopy = JSON.stringify(feature.geometry);
43+
44+
// 编辑器重置数据
45+
const editor = this.editor;
46+
editor.set({ type: 'FeatureCollection', "features": [feature] });
47+
48+
if (feature.geometry.type === 'Point')
49+
editor.changeMode('simple_select', { featureIds: [fId] })
50+
else
51+
editor.changeMode('direct_select', { featureId: fId });
52+
53+
const handleSelectChange = (e: any) => {
54+
const cFeature = editor.get(fId);
55+
56+
// 当前选择图形失去选择状态 完成修改
57+
if (e.features.length === 0 && cFeature) {
58+
// 若发生改变
59+
if (geometryCopy === JSON.stringify(cFeature.geometry)) {
60+
onChange(cFeature as TIdentityGeoJSONFeature);
61+
}
62+
63+
// 删除编辑数据
64+
this.map.off('draw.selectionchange', handleSelectChange);
65+
editor.changeMode('draw_point');
66+
editor.deleteAll();
67+
}
68+
}
69+
70+
this.map.on('draw.selectionchange', handleSelectChange);
71+
}
72+
}

0 commit comments

Comments
 (0)