forked from maptalks/maptalks.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeometryEditor.ts
More file actions
1603 lines (1486 loc) · 61.6 KB
/
GeometryEditor.ts
File metadata and controls
1603 lines (1486 loc) · 61.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { INTERNAL_LAYER_PREFIX } from '../../core/Constants';
import { isNil, isNumber, sign, removeFromArray, UID, isFunction } from '../../core/util';
import { lowerSymbolOpacity } from '../../core/util/style';
import Class from '../../core/Class';
import Eventable from '../../core/Eventable';
import Point from '../../geo/Point';
import Coordinate from '../../geo/Coordinate';
import { Marker, TextBox, LineString, Polygon, Circle, Ellipse, Sector, Rectangle, Geometry } from '../';
import EditHandle from '../../renderer/edit/EditHandle';
import EditOutline from '../../renderer/edit/EditOutline';
import { loadFunctionTypes } from '../../core/mapbox';
import * as Symbolizers from '../../renderer/geometry/symbolizers';
import { GeometryEditOptionsType, GeometryEditSymbolType } from '../ext/Geometry.Edit';
import { getDefaultBBOX, pointsBBOX } from '../../core/util/bbox';
import Extent from '../../geo/Extent';
import { MapStateCache } from '../../map/MapStateCache';
const EDIT_STAGE_LAYER_PREFIX = INTERNAL_LAYER_PREFIX + '_edit_stage_';
const SHADOW_DRAG_EVENTS = 'dragend dragstart';
type GeometryEvents = {
'symbolchange': any,
// prevent _exeAndReset when dragging geometry in gl layers
'dragstart': any,
'dragend': any,
'positionchange shapechange': any,
}
function createHandleSymbol(markerType: string, opacity: number): GeometryEditSymbolType {
return {
'markerType': markerType,
'markerFill': '#fff',
'markerLineColor': '#000',
'markerLineWidth': 2,
'markerWidth': 10,
'markerHeight': 10,
'opacity': opacity
};
}
/**
* coordinate to containerPoint with altitude
* @param map
* @param coordinate
* @returns
*/
function coordinatesToContainerPoint(map, coordinate) {
const glRes = map.getGLRes();
//coordinates to glpoint
const renderPoints = map.coordToPointAtRes(coordinate, glRes);
const altitude = coordinate.z || 0;
const point = map._pointAtResToContainerPoint(renderPoints, glRes, altitude);
return point;
}
export function fixHandlePointCoordinates(geometry: Geometry, vertex: Coordinate, dragContainerPoint: Point) {
const map = geometry.getMap();
if (!vertex || vertex.z === 0) {
return map.containerPointToCoord(dragContainerPoint)
}
const altitude = vertex.z;
const glRes = map.getGLRes();
//coordinates to glpoint
const renderPoints = map.coordToPointAtRes(vertex, glRes);
//没有海拔下的屏幕坐标
const point1 = map._pointAtResToContainerPoint(renderPoints, glRes, 0);
//有海拔下的屏幕坐标
const point2 = map._pointAtResToContainerPoint(renderPoints, glRes, altitude);
//屏幕坐标的偏移量
const offset = point2.sub(point1);
const containerPoint = dragContainerPoint.sub(offset);
const coordinates = map.containerPointToCoord(containerPoint);
coordinates.z = 0;
const isPoint = !geometry.getGeometries && geometry.isPoint;
if (isPoint) {
coordinates.z = altitude;
}
return coordinates;
}
function onHandleDragstart(param: Record<string, any>): boolean {
const geometryEditor = this.target;
const opts = this.paramOptions;
geometryEditor._updating = true;
if (opts.onDown) {
opts.onDown.call(geometryEditor, param['containerPoint'], param);
/**
* 更改几何图形启动事件,在拖动以更改几何图形时激发
* @english
* change geometry shape start event, fired when drag to change geometry shape.
*
* @event Geometry#handledragstart
* @type {Object}
* @property {String} type - handledragstart
* @property {Geometry} target - the geometry fires the event
*/
geometryEditor._geometry.fire('handledragstart');
}
return false;
}
function onHandleDragging(param: Record<string, any>): boolean {
const geometryEditor = this.target;
const opts = this.paramOptions;
geometryEditor._hideContext();
if (opts.onMove) {
opts.onMove.call(geometryEditor, param);
/**
* 更改几何图形事件,在拖动以更改几何图形时激发
* @english
* changing geometry shape event, fired when dragging to change geometry shape.
*
* @event Geometry#handledragging
* @type {Object}
* @property {String} type - handledragging
* @property {Geometry} target - the geometry fires the event
*/
geometryEditor._geometry.fire('handledragging');
}
return false;
}
function onHandleDragEnd(ev: Record<string, any>): boolean {
const geometryEditor = this.target;
const opts = this.paramOptions;
if (opts.onUp) {
//run mouseup code for handle delete etc
opts.onUp.call(geometryEditor, ev);
/**
* changed geometry shape event, fired when drag end to change geometry shape.
*
* @event Geometry#handledragend
* @type {Object}
* @property {String} type - handledragend
* @property {Geometry} target - the geometry fires the event
*/
geometryEditor._geometry.fire('handledragend');
}
geometryEditor._updating = false;
return false;
}
const options: GeometryEditOptionsType = {
//fix outline's aspect ratio when resizing
'fixAspectRatio': false,
// geometry's symbol when editing
'symbol': null,
'removeVertexOn': 'contextmenu',
//symbols of edit handles
'centerHandleSymbol': createHandleSymbol('ellipse', 1),
'vertexHandleSymbol': createHandleSymbol('square', 1),
'newVertexHandleSymbol': createHandleSymbol('square', 0.4),
'collision': false,
'collisionBufferSize': 0,
'vertexZIndex': 0,
'newVertexZIndex': 0,
'shadowDraggable': false
};
/**
* 内部使用的几何图形编辑器
* @english
* Geometry editor used internally for geometry editing.
* @category geometry
* @protected
* @extends Class
* @mixes Eventable
*/
class GeometryEditor extends Eventable(Class) {
//@internal
_geometry: any;
//@internal
_originalSymbol: any
//@internal
_shadowLayer: any
//@internal
_shadow?: Geometry;
//@internal
_geometryDraggble: boolean
//@internal
_history: any
//@internal
_historyPointer: any
//@internal
_editOutline: any
//@internal
_refreshHooks: Array<any>
//@internal
_updating: boolean
editing: boolean;
options: GeometryEditOptionsType;
/**
* @param {Geometry} geometry geometry to edit
* @param {Object} [opts=null] options
* @param {Object} [opts.symbol=null] symbol of being edited.
*/
constructor(geometry, opts: GeometryEditOptionsType) {
super(opts);
this._geometry = geometry;
if (!this._geometry) {
return;
}
}
/**
* 获取地图对象
* @english
* Get map
* @return {Map} map
*/
getMap(): any {
return this._geometry.getMap();
}
/**
* 准备编辑
* @english
* Prepare to edit
*/
prepare(): void {
const map = this.getMap();
if (!map) {
return;
}
map.on('drawtopstart', this._refresh, this);
/**
* reserve the original symbol
*/
if (this.options['symbol']) {
this._originalSymbol = this._geometry.getSymbol();
this._geometry.setSymbol(this.options['symbol']);
}
this._prepareEditStageLayer();
}
//@internal
_prepareEditStageLayer(): void {
const layer = this._geometry.getLayer();
if (layer.options['renderer'] !== 'canvas') {
// doesn't need shadow if it's webgl or gpu renderer
return;
}
const map = this.getMap();
const uid = UID();
const shadowId = EDIT_STAGE_LAYER_PREFIX + uid + '_shadow';
this._shadowLayer = map.getLayer(shadowId);
if (!this._shadowLayer) {
const LayerType = layer.constructor;
this._shadowLayer = new LayerType(shadowId);
map.addLayer(this._shadowLayer);
}
}
/**
* 开始编辑
* @english
* Start to edit
*/
start(): void {
if (!this._geometry || !this._geometry.getMap() || this._geometry.editing) {
return;
}
this.editing = true;
this.prepare();
const geometry = this._geometry;
let shadow;
const layer = this._geometry.getLayer();
const needShadow = layer.options['renderer'] === 'canvas';
this._geometryDraggble = geometry.options['draggable'];
if (needShadow) {
geometry.config('draggable', false);
//edits are applied to a shadow of geometry to improve performance.
shadow = geometry.copy();
shadow.setSymbol(geometry._getInternalSymbol());
//geometry copy没有将event复制到新建的geometry,对于编辑这个功能会存在一些问题
//原geometry上可能绑定了其它监听其click/dragging的事件,在编辑时就无法响应了.
shadow.copyEventListeners(geometry);
if (geometry._getParent()) {
shadow.copyEventListeners(geometry._getParent());
}
shadow._setEventTarget(geometry);
//drag shadow by center handle instead.
shadow.setId(null).config({
'draggable': this.options.shadowDraggable
});
this._shadow = shadow;
geometry.hide();
} else if (geometry instanceof Marker) {
geometry.config('draggable', true);
}
this._switchGeometryEvents('on');
if (geometry instanceof Marker ||
geometry instanceof Circle ||
geometry instanceof Rectangle ||
geometry instanceof Ellipse) {
//ouline has to be added before shadow to let shadow on top of it, otherwise shadow's events will be overrided by outline
this._createOrRefreshOutline();
}
if (this._shadowLayer) {
this._shadowLayer.bringToFront().addGeometry(shadow);
}
if (!(geometry instanceof Marker)) {
this._createCenterHandle();
} else if (shadow) {
shadow.config('draggable', true);
shadow.on('dragend', this._onMarkerDragEnd, this);
}
if ((geometry instanceof Marker) && this.options['resize'] !== false) {
this.createMarkerEditor();
} else if (geometry instanceof Circle) {
this.createCircleEditor();
} else if (geometry instanceof Rectangle) {
this.createEllipseOrRectEditor();
} else if (geometry instanceof Ellipse) {
this.createEllipseOrRectEditor();
} else if (geometry instanceof Sector) {
// TODO: createSectorEditor
} else if ((geometry instanceof Polygon) ||
(geometry instanceof LineString)) {
this.createPolygonEditor();
}
}
/**
* 停止编辑
* @english
* Stop editing
*/
stop(): void {
delete this._history;
delete this._historyPointer;
delete this._editOutline;
this._switchGeometryEvents('off');
const map = this.getMap();
if (!map) {
this.fire('remove');
return;
}
this._geometry.config('draggable', this._geometryDraggble);
if (this._shadow) {
this._shadow.off(SHADOW_DRAG_EVENTS, this._shadowDragEvent, this);
delete this._shadow;
delete this._geometryDraggble;
this._geometry.show();
}
if (this._shadowLayer) {
this._shadowLayer.remove();
delete this._shadowLayer;
}
this._refreshHooks = [];
if (this.options['symbol']) {
this._geometry.setSymbol(this._originalSymbol);
delete this._originalSymbol;
}
this.editing = false;
this.fire('remove');
}
/**
* 编辑器是否在编辑
* @english
* Whether the editor is editing
* @return {Boolean}
*/
isEditing(): boolean {
if (isNil(this.editing)) {
return false;
}
return this.editing;
}
//@internal
_getGeometryEvents(): GeometryEvents {
return {
'symbolchange': this._onGeoSymbolChange,
// prevent _exeAndReset when dragging geometry in gl layers
'dragstart': this._onDragStart,
'dragend': this._onDragEnd,
'positionchange shapechange': this._exeAndReset,
};
}
//@internal
_switchGeometryEvents(oper: any): void {
if (this._geometry) {
const events = this._getGeometryEvents();
for (const p in events) {
this._geometry[oper](p, events[p], this);
}
}
}
//@internal
_onGeoSymbolChange(param: any): void {
if (this._shadow) {
this._shadow.setSymbol(param.target._getInternalSymbol());
}
}
//@internal
_onMarkerDragEnd(): void {
this._update('setCoordinates', (this._shadow as Marker).getCoordinates().toArray());
}
/**
* 创建几何图形的矩形轮廓
* @english
* create rectangle outline of the geometry
* @private
*/
//@internal
_createOrRefreshOutline(): any {
const geometry = this._geometry;
const outline = this._editOutline;
if (!outline) {
this._editOutline = new EditOutline(this, this.getMap());
this._addRefreshHook(this._createOrRefreshOutline);
}
const points = this._editOutline.points;
if (geometry instanceof Marker) {
this._editOutline.setPoints(geometry.getContainerExtent().toArray(points));
} else {
// const map = this.getMap();
// const extent = geometry._getPrjExtent();
// points = extent.toArray(points);
// points.forEach(c => map.prjToContainerPoint(c, null, c));
// this._editOutline.setPoints(points);
const coordinates = geometry.getShell();
const editCenter = geometry._getEditCenter();
const bbox = getDefaultBBOX();
pointsBBOX(coordinates, bbox);
const extent = new Extent(bbox[0], bbox[1], bbox[2], bbox[3]);
const map = this.getMap();
const points = extent.toArray().map(c => {
c.z = editCenter.z;
return coordinatesToContainerPoint(map, c);
})
this._editOutline.setPoints(points);
}
return outline;
}
_shadowDragEvent(e) {
const type = e.type;
if (type === 'dragend') {
//update Geometry coordinates by shadow
this._updateCoordFromShadow();
}
}
//@internal
_createCenterHandle(): void {
const map = this.getMap();
const symbol = this.options['centerHandleSymbol'];
let shadow;
if (this._shadow) {
this._shadow.off(SHADOW_DRAG_EVENTS, this._shadowDragEvent, this);
}
// const cointainerPoint = map.coordToContainerPoint(this._geometry.getCenter());
if (this.options.shadowDraggable && this._shadow) {
this._shadow.on(SHADOW_DRAG_EVENTS, this._shadowDragEvent, this);
}
const cointainerPoint = coordinatesToContainerPoint(map, this._geometry._getEditCenter());
const handle = this.createHandle(cointainerPoint, {
ignoreCollision: true,
'symbol': symbol,
'cursor': 'move',
onDown: (): void => {
if (this._shadow) {
shadow = this._shadow.copy();
const symbol = lowerSymbolOpacity(shadow._getInternalSymbol(), 0.5);
shadow.setSymbol(symbol).addTo(this._geometry.getLayer());
}
},
onMove: (param): void => {
const offset = param['coordOffset'];
if (shadow) {
shadow.translate(offset);
} else {
this._geometry.translate(offset);
}
},
onUp: (): void => {
if (shadow) {
const shadowFirst = shadow.getFirstCoordinate();
const first = this._geometry.getFirstCoordinate();
const offset = shadowFirst.sub(first);
this._update('translate', offset);
shadow.remove();
}
}
});
this._addRefreshHook((): void => {
// const center = this._geometry.getCenter();
// handle.setContainerPoint(map.coordToContainerPoint(center));
const center = this._geometry._getEditCenter();
handle.setContainerPoint(coordinatesToContainerPoint(map, center));
});
}
//@internal
_createHandleInstance(containerPoint: Point, opts: GeometryEditOptionsType): EditHandle {
opts = opts || {};
const map = this.getMap();
const symbol = loadFunctionTypes(opts['symbol'], (): any => {
const cache = MapStateCache[map.id];
const zoom = cache ? cache.zoom : map.getZoom();
const pitch = cache ? cache.pitch : map.getPitch();
const bearing = cache ? cache.bearing : map.getBearing();
return [
zoom,
{
'{bearing}': bearing,
'{pitch}': pitch,
'{zoom}': zoom
}
];
});
const removeVertexOn = this.options['removeVertexOn'];
const handle = new EditHandle(this, map, { symbol, cursor: opts['cursor'], events: removeVertexOn as any, ignoreCollision: (opts as any).ignoreCollision });
handle.setContainerPoint(containerPoint);
return handle;
}
createHandle(containerPoint: any, opts: any): EditHandle {
if (!opts) {
opts = {};
}
const handle = this._createHandleInstance(containerPoint, opts);
handle.paramOptions = opts;
handle.on('dragstart', onHandleDragstart);
handle.on('dragging', onHandleDragging);
handle.on('dragend', onHandleDragEnd);
//拖动移图
if (opts.onRefresh) {
handle.refresh = opts.onRefresh;
}
return handle;
}
/**
* 为几何图形创建可以调整大小的事件
* @english
* create resize handles for geometry that can resize.
* @param {Array} blackList handle indexes that doesn't display, to prevent change a geometry's coordinates
* @param {fn} onHandleMove callback
* @private
*/
//@internal
_createResizeHandles(blackList: Array<any>, onHandleMove: any, onHandleUp: any): any {
//cursor styles.
const cursors = [
'nw-resize', 'n-resize', 'ne-resize',
'w-resize', 'e-resize',
'sw-resize', 's-resize', 'se-resize'
];
//defines dragOnAxis of resize handle
const axis = [
null, 'y', null,
'x', 'x',
null, 'y', null
];
const geometry = this._geometry;
//marker做特殊处理,利用像素求锚点
const isMarker = geometry instanceof Marker;
let coords = [];
function getResizeAnchors(): any {
if (isMarker) {
const ext = geometry.getContainerExtent();
return [
// ext.getMin(),
new Point(ext['xmin'], ext['ymin']),
new Point((ext['xmax'] + ext['xmin']) / 2, ext['ymin']),
new Point(ext['xmax'], ext['ymin']),
new Point(ext['xmin'], (ext['ymin'] + ext['ymax']) / 2),
new Point(ext['xmax'], (ext['ymin'] + ext['ymax']) / 2),
new Point(ext['xmin'], ext['ymax']),
new Point((ext['xmax'] + ext['xmin']) / 2, ext['ymax']),
new Point(ext['xmax'], ext['ymax'])
];
}
// const ext = geometry._getPrjExtent();
//Rect,Ellipse,Circle etc
const coordinates = geometry.getShell();
const editCenter = geometry._getEditCenter();
const bbox = getDefaultBBOX();
pointsBBOX(coordinates, bbox);
const extent = new Extent(bbox[0], bbox[1], bbox[2], bbox[3]);
coords = [
new Coordinate(extent['xmin'], extent['ymax']),
new Coordinate((extent['xmax'] + extent['xmin']) / 2, extent['ymax']),
new Coordinate(extent['xmax'], extent['ymax']),
new Coordinate(extent['xmin'], (extent['ymax'] + extent['ymin']) / 2),
new Coordinate(extent['xmax'], (extent['ymax'] + extent['ymin']) / 2),
new Coordinate(extent['xmin'], extent['ymin']),
new Coordinate((extent['xmax'] + extent['xmin']) / 2, extent['ymin']),
new Coordinate(extent['xmax'], extent['ymin']),
];
return coords.map(c => {
c.z = editCenter.z;
return coordinatesToContainerPoint(map, c);
})
// return [
// // ext.getMin(),
// // new Point(ext['xmin'], ext['ymax']),
// // new Point((ext['xmax'] + ext['xmin']) / 2, ext['ymax']),
// // new Point(ext['xmax'], ext['ymax']),
// // new Point(ext['xmin'], (ext['ymax'] + ext['ymin']) / 2),
// // new Point(ext['xmax'], (ext['ymax'] + ext['ymin']) / 2),
// // new Point(ext['xmin'], ext['ymin']),
// // new Point((ext['xmax'] + ext['xmin']) / 2, ext['ymin']),
// // new Point(ext['xmax'], ext['ymin']),
// ];
}
if (!blackList) {
blackList = [];
}
const me = this;
const resizeHandles = [],
anchorIndexes = {},
map = this.getMap(),
handleSymbol = this.options['vertexHandleSymbol'];
const fnLocateHandles = (): void => {
const anchors = getResizeAnchors();
for (let i = 0; i < anchors.length; i++) {
//ignore anchors in blacklist
if (Array.isArray(blackList)) {
const isBlack = blackList.some(ele => ele === i);
if (isBlack) {
continue;
}
}
const anchor = anchors[i], point = anchor, coord = coords[i];
// point = isMarker ? anchor : map.prjToContainerPoint(anchor);
if (resizeHandles.length < (anchors.length - blackList.length)) {
const handle = this.createHandle(point, {
'symbol': handleSymbol,
'cursor': cursors[i],
'axis': axis[i],
onMove: (function (_index: number): any {
return function (e: any): void {
me._updating = true;
onHandleMove(e.containerPoint, _index);
geometry.fire('resizing');
};
})(i),
onUp: (): void => {
me._updating = false;
onHandleUp();
}
});
// handle.setId(i);
anchorIndexes[i] = resizeHandles.length;
resizeHandles.push(handle);
//record handle coordinates
handle.coord = coord;
} else {
//record handle coordinates
resizeHandles[anchorIndexes[i]].coord = coord;
resizeHandles[anchorIndexes[i]].setContainerPoint(point);
}
}
};
fnLocateHandles();
//refresh hooks to refresh handles' coordinates
this._addRefreshHook(fnLocateHandles);
return resizeHandles;
}
/**
* 创建标记编辑器
* @english
* Create marker editor
* @private
*/
createMarkerEditor(): void {
const geometryToEdit = this._shadow || this._geometry,
map = this.getMap();
if (!geometryToEdit._canEdit()) {
if (console) {
console.warn('A marker can\'t be resized with symbol:', geometryToEdit.getSymbol());
}
return;
}
if (!this._history) {
this._recordHistory(getUpdates());
}
//only image marker and vector marker can be edited now.
const symbol = geometryToEdit._getInternalSymbol();
const dxdy = new Point(0, 0);
if (isNumber(symbol['markerDx'])) {
dxdy.x = symbol['markerDx'];
}
if (isNumber(symbol['markerDy'])) {
dxdy.y = symbol['markerDy'];
}
let blackList = null;
let verticalAnchor = 'middle';
let horizontalAnchor = 'middle';
if (Symbolizers.VectorMarkerSymbolizer.test(symbol)) {
const type = symbol['markerType'];
if (type === 'pin' || type === 'pie' || type === 'bar') {
//as these types of markers' anchor stands on its bottom
blackList = [5, 6, 7];
verticalAnchor = 'bottom';
} else if (type === 'rectangle') {
blackList = [0, 1, 2, 3, 5];
verticalAnchor = 'top';
horizontalAnchor = 'left';
}
} else if (Symbolizers.ImageMarkerSymbolizer.test(symbol) ||
Symbolizers.VectorPathMarkerSymbolizer.test(symbol)) {
verticalAnchor = 'bottom';
blackList = [5, 6, 7];
}
//defines what can be resized by the handle
//0: resize width; 1: resize height; 2: resize both width and height.
const resizeAbilities = [
2, 1, 2,
0, 0,
2, 1, 2
];
let aspectRatio;
if (this.options['fixAspectRatio']) {
const size = geometryToEdit.getSize();
aspectRatio = size.width / size.height;
}
const resizeHandles = this._createResizeHandles(blackList, (containerPoint: any, i: number): void => {
if (blackList && blackList.indexOf(i) >= 0) {
//need to change marker's coordinates
const newCoordinates = map.containerPointToCoordinate(containerPoint.sub(dxdy));
const coordinates = geometryToEdit.getCoordinates();
newCoordinates.x = coordinates.x;
geometryToEdit.setCoordinates(newCoordinates);
this._updateCoordFromShadow(true);
// geometryToEdit.setCoordinates(newCoordinates);
//coordinates changed, and use mirror handle instead to caculate width and height
const mirrorHandle = resizeHandles[resizeHandles.length - 1 - i];
const mirror = mirrorHandle.getContainerPoint();
containerPoint = mirror;
}
//caculate width and height
// const viewCenter = map.coordToContainerPoint(geometryToEdit.getCoordinates()).add(dxdy),
const viewCenter = coordinatesToContainerPoint(map, geometryToEdit._getEditCenter()).add(dxdy),
symbol = geometryToEdit._getInternalSymbol();
const wh = containerPoint.sub(viewCenter);
if (verticalAnchor === 'bottom' && containerPoint.y > viewCenter.y) {
wh.y = 0;
}
//if this marker's anchor is on its bottom, height doesn't need to multiply by 2.
const vr = verticalAnchor === 'middle' ? 2 : 1;
const hr = horizontalAnchor === 'left' ? 1 : 2;
let width = Math.abs(wh.x) * hr,
height = Math.abs(wh.y) * vr;
if (aspectRatio) {
width = Math.max(width, height * aspectRatio);
height = width / aspectRatio;
}
const ability = resizeAbilities[i];
if (!(geometryToEdit instanceof TextBox)) {
if (aspectRatio || ability === 0 || ability === 2) {
symbol['markerWidth'] = Math.min(width, this._geometry.options['maxMarkerWidth'] || Infinity);
}
if (aspectRatio || ability === 1 || ability === 2) {
symbol['markerHeight'] = Math.min(height, this._geometry.options['maxMarkerHeight'] || Infinity);
}
geometryToEdit.setSymbol(symbol);
if (geometryToEdit !== this._geometry) {
this._geometry.setSymbol(symbol);
}
} else {
if (aspectRatio || ability === 0 || ability === 2) {
geometryToEdit.setWidth(width);
if (geometryToEdit !== this._geometry) {
this._geometry.setWidth(width);
}
}
if (aspectRatio || ability === 1 || ability === 2) {
geometryToEdit.setHeight(height);
if (geometryToEdit !== this._geometry) {
this._geometry.setHeight(height);
}
}
}
}, (): void => {
this._update(getUpdates());
});
function getUpdates(): any {
const updates = [
['setCoordinates', geometryToEdit.getCoordinates().toArray()]
];
if (geometryToEdit instanceof TextBox) {
updates.push(['setWidth', geometryToEdit.getWidth()]);
updates.push(['setHeight', geometryToEdit.getHeight()]);
} else {
updates.push(['setSymbol', geometryToEdit.getSymbol()]);
}
return updates;
}
}
/**
* 创建圆形编辑器
* @english
* Create circle editor
* @private
*/
createCircleEditor(): void {
const geo = this._shadow || this._geometry;
const map = this.getMap();
if (!this._history) {
this._recordHistory([
['setCoordinates', geo.getCoordinates().toArray()],
['setRadius', geo.getRadius()]
]);
}
this._createResizeHandles(null, handleContainerPoint => {
const center = geo.getCenter();
// const mouseCoordinate = map.containerPointToCoord(handleContainerPoint);
const mouseCoordinate = fixHandlePointCoordinates(geo, center, handleContainerPoint);
const wline = new LineString([[center.x, center.y], [mouseCoordinate.x, center.y]]);
const hline = new LineString([[center.x, center.y], [center.x, mouseCoordinate.y]]);
const r = Math.max(map.computeGeometryLength(wline), map.computeGeometryLength(hline));
geo.setRadius(r);
if (geo !== this._geometry) {
this._geometry.setRadius(r);
}
}, (): void => {
this._update('setRadius', geo.getRadius());
});
}
/**
* 创建椭圆或者矩形编辑器
* @english
* editor of ellipse or rectangle
* @private
*/
createEllipseOrRectEditor(): void {
//defines what can be resized by the handle
//0: resize width; 1: resize height; 2: resize both width and height.
const resizeAbilities = [
2, 1, 2,
0, 0,
2, 1, 2
];
const geometryToEdit = this._shadow || this._geometry;
if (!this._history) {
this._recordHistory(getUpdates());
}
const map = this.getMap();
const isRect = this._geometry instanceof Rectangle;
let aspectRatio;
if (this.options['fixAspectRatio']) {
aspectRatio = geometryToEdit.getWidth() / geometryToEdit.getHeight();
}
const resizeHandles = this._createResizeHandles(null, (mouseContainerPoint: any, i: number): void => {
//ratio of width and height
const r = isRect ? 1 : 2;
let pointSub, w, h;
const handle = resizeHandles[i];
const targetPoint = handle.getContainerPoint(); //mouseContainerPoint;
const ability = resizeAbilities[i];
if (isRect) {
const mirror = resizeHandles[7 - i];
const mirrorContainerPoint = mirror.getContainerPoint();
pointSub = targetPoint.sub(mirrorContainerPoint);
const absSub = pointSub.abs();
w = map.pixelToDistance(absSub.x, 0);
h = map.pixelToDistance(0, absSub.y);
const size = geometryToEdit.getSize();
const geoCoord = geometryToEdit.getCoordinates();
const width = geometryToEdit.getWidth();
const height = geometryToEdit.getHeight();
// const mouseCoordinate = map.containerPointToCoord(mouseContainerPoint);
const mirrorCoordinate = mirror.coord;
const mouseCoordinate = fixHandlePointCoordinates(geometryToEdit, geoCoord, mouseContainerPoint);
const wline = new LineString([[mirrorCoordinate.x, mirrorCoordinate.y], [mouseCoordinate.x, mirrorCoordinate.y]]);
const hline = new LineString([[mirrorCoordinate.x, mirrorCoordinate.y], [mirrorCoordinate.x, mouseCoordinate.y]]);
//fix distance cal error
w = map.computeGeometryLength(wline);
h = map.computeGeometryLength(hline);
if (ability === 0) {
// changing width
// - - -
// 0 0
// - - -
// Rectangle's northwest's y is (y - height / 2)
if (aspectRatio) {
// update rectangle's height with aspect ratio
absSub.y = absSub.x / aspectRatio;
size.height = Math.abs(absSub.y);
h = w / aspectRatio;
}
targetPoint.y = mirrorContainerPoint.y - size.height / 2;
mouseCoordinate.y = geoCoord.y;
if (i === 4) {
mouseCoordinate.x = Math.min(mouseCoordinate.x, geoCoord.x);
} else {
// use locate instead of containerPoint to fix precision problem
const mirrorCoord = map.locate(geoCoord, width, 0);
mouseCoordinate.x = map.locate(new Coordinate(mirrorCoord.x, mouseCoordinate.y), -w, 0).x;
}
} else if (ability === 1) {
// changing height
// - 1 -
// | |
// - 1 -
// Rectangle's northwest's x is (x - width / 2)
if (aspectRatio) {
// update rectangle's width with aspect ratio
absSub.x = absSub.y * aspectRatio;
size.width = Math.abs(absSub.x);
w = h * aspectRatio;
}
targetPoint.x = mirrorContainerPoint.x - size.width / 2;
mouseCoordinate.x = geoCoord.x;
mouseCoordinate.y = Math.max(mouseCoordinate.y, mirrorCoordinate.y);
} else {
// corner handles, relocate the target point according to aspect ratio.
if (aspectRatio) {
if (w > h * aspectRatio) {
h = w / aspectRatio;
targetPoint.y = mirrorContainerPoint.y + absSub.x * sign(pointSub.y) / aspectRatio;
} else {
w = h * aspectRatio;
targetPoint.x = mirrorContainerPoint.x + absSub.y * sign(pointSub.x) * aspectRatio;
}
}
// anchor at northwest and south west
if (i === 0 || i === 5) {
// use locate instead of containerPoint to fix precision problem
const mirrorCoord = i === 0 ? map.locate(geoCoord, width, 0) : map.locate(geoCoord, width, -height);
mouseCoordinate.x = map.locate(new Coordinate(mirrorCoord.x, mouseCoordinate.y), -w, 0).x;
} else {
mouseCoordinate.x = Math.min(mouseCoordinate.x, mirrorCoordinate.x);
}
mouseCoordinate.y = Math.max(mouseCoordinate.y, mirrorCoordinate.y);
}
//change rectangle's coordinates
// const newCoordinates = map.viewPointToCoordinate(new Point(Math.min(targetPoint.x, mirrorContainerPoint.x), Math.min(targetPoint.y, mirrorContainerPoint.y)));
mouseCoordinate.z = geoCoord.z;
geometryToEdit.setCoordinates(mouseCoordinate);
this._updateCoordFromShadow(true);
// geometryToEdit.setCoordinates(newCoordinates);
} else {
// const viewCenter = map.coordToViewPoint(geometryToEdit.getCenter());
// pointSub = viewCenter.sub(targetPoint)._abs();
// w = map.pixelToDistance(pointSub.x, 0);
// h = map.pixelToDistance(0, pointSub.y);
// if (aspectRatio) {
// w = Math.max(w, h * aspectRatio);
// h = w / aspectRatio;
// }
const center = geometryToEdit.getCenter();
// const mouseCoordinate = map.containerPointToCoord(targetPoint);
const mouseCoordinate = fixHandlePointCoordinates(geometryToEdit, center, mouseContainerPoint);
const wline = new LineString([[center.x, center.y], [mouseCoordinate.x, center.y]]);
const hline = new LineString([[center.x, center.y], [center.x, mouseCoordinate.y]]);
w = map.computeGeometryLength(wline);
h = map.computeGeometryLength(hline);
if (aspectRatio) {