-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
DrawGeodesic.js
1102 lines (903 loc) · 29.6 KB
/
DrawGeodesic.js
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
// Fixes other parts of L.Draw where this function is used to get endpoints
L.Geodesic.prototype.getLatLngs = function () {
if (!this.points || this.points.length === 0)
return [];
return this.points[0];
}
// Does what GeodesicLine#getLatLngs() should do
L.Geodesic.prototype.getActualLatLngs = function () {
return this._latlngs;
}
// Writing these functions as class methods will result in an error being thrown. I don't know why.
function _createGeodesic (coords, opts = {}) {
let geodesic = new L.Geodesic(coords, {...opts, wrap: true});
geodesic.geom.geodesic.ellipsoid.a = 6378137;
geodesic.geom.geodesic.ellipsoid.b = 6378137;
geodesic.geom.geodesic.ellipsoid.f = 0;
geodesic.updateGeometry();
return geodesic;
}
/**
* Redraws Leaflet layer or geodesic line
* @param poly {L.Layer | L.Geodesic} Layer to redraw
*/
L.redrawLayer = function (poly) {
if (poly.updateGeometry)
poly.updateGeometry();
else
poly.redraw();
}
/**
* @class L.Draw.Polyline
* @aka Draw.Polyline
* @inherits L.Draw.Feature
*/
L.Draw.Polyline = L.Draw.Feature.extend({
statics: {
TYPE: 'polyline'
},
Poly: L.Geodesic,
options: {
allowIntersection: true,
repeatMode: false,
drawError: {
color: '#b00b00',
timeout: 2500
},
icon: new L.DivIcon({
iconSize: new L.Point(8, 8),
className: 'leaflet-div-icon leaflet-editing-icon'
}),
touchIcon: new L.DivIcon({
iconSize: new L.Point(20, 20),
className: 'leaflet-div-icon leaflet-editing-icon leaflet-touch-icon'
}),
guidelineDistance: 20,
maxGuideLineLength: 4000,
shapeOptions: {
stroke: true,
color: '#3388ff',
weight: 4,
opacity: 0.5,
fill: false,
clickable: true
},
metric: true, // Whether to use the metric measurement system or imperial
feet: true, // When not metric, to use feet instead of yards for display.
nautic: false, // When not metric, not feet use nautic mile for display
showLength: true, // Whether to display distance in the tooltip
zIndexOffset: 2000, // This should be > than the highest z-index any map layers
factor: 1, // To change distance calculation
maxPoints: 0 // Once this number of points are placed, finish shape
},
// @method initialize(): void
initialize: function (map, options) {
// if touch, switch to touch icon
if (L.Browser.touch) {
this.options.icon = this.options.touchIcon;
}
// Need to set this here to ensure the correct message is used.
this.options.drawError.message = L.drawLocal.draw.handlers.polyline.error;
// Merge default drawError options with custom options
if (options && options.drawError) {
options.drawError = L.Util.extend({}, this.options.drawError, options.drawError);
}
// Save the type so super can fire, need to do this as cannot do this.TYPE :(
this.type = L.Draw.Polyline.TYPE;
this.options.shapeOptions.wrap = true;
L.Draw.Feature.prototype.initialize.call(this, map, options);
this.guideLine = _createGeodesic([], {...this.options.shapeOptions, dashArray: "4 8"});
},
// @method addHooks(): void
// Add listener hooks to this handler
addHooks: function () {
L.Draw.Feature.prototype.addHooks.call(this);
if (this._map) {
this._markers = [];
this._markerGroup = new L.LayerGroup();
this._map.addLayer(this._markerGroup);
this._poly = _createGeodesic([], this.options.shapeOptions);
this._tooltip.updateContent(this._getTooltipText());
// Make a transparent marker that will used to catch click events. These click
// events will create the vertices. We need to do this so we can ensure that
// we can create vertices over other map layers (markers, vector layers). We
// also do not want to trigger any click handlers of objects we are clicking on
// while drawing.
if (!this._mouseMarker) {
this._mouseMarker = new L.Marker(this._map.getCenter(), {
icon: L.divIcon({
className: 'leaflet-mouse-marker',
iconAnchor: [20, 20],
iconSize: [40, 40]
}),
opacity: 0,
zIndexOffset: this.options.zIndexOffset
});
}
this._mouseMarker
.on('mouseout', this._onMouseOut, this)
.on('mousemove', this._onMouseMove, this) // Necessary to prevent 0.8 stutter
.on('mousedown', this._onMouseDown, this)
.on('mouseup', this._onMouseUp, this) // Necessary for 0.8 compatibility
.addTo(this._map);
this._map
.on('mouseup', this._onMouseUp, this) // Necessary for 0.7 compatibility
.on('mousemove', this._onMouseMove, this)
.on('zoomlevelschange', this._onZoomEnd, this)
.on('touchstart', this._onTouch, this)
.on('zoomend', this._onZoomEnd, this);
}
},
// @method removeHooks(): void
// Remove listener hooks from this handler.
removeHooks: function () {
L.Draw.Feature.prototype.removeHooks.call(this);
this._clearHideErrorTimeout();
this._cleanUpShape();
// remove markers from map
this._map.removeLayer(this._markerGroup);
delete this._markerGroup;
delete this._markers;
this._map.removeLayer(this._poly);
delete this._poly;
this._mouseMarker
.off('mousedown', this._onMouseDown, this)
.off('mouseout', this._onMouseOut, this)
.off('mouseup', this._onMouseUp, this)
.off('mousemove', this._onMouseMove, this);
this._map.removeLayer(this._mouseMarker);
delete this._mouseMarker;
// clean up DOM
this._clearGuides();
this._map
.off('mouseup', this._onMouseUp, this)
.off('mousemove', this._onMouseMove, this)
.off('zoomlevelschange', this._onZoomEnd, this)
.off('zoomend', this._onZoomEnd, this)
.off('touchstart', this._onTouch, this)
.off('click', this._onTouch, this);
},
// @method deleteLastVertex(): void
// Remove the last vertex from the polyline, removes polyline from map if only one point exists.
deleteLastVertex: function () {
if (this._markers.length <= 1) {
return;
}
var lastMarker = this._markers.pop(),
poly = this._poly,
// Replaces .spliceLatLngs()
latlngs = poly.getLatLngs(),
latlng = latlngs.splice(-1, 1)[0];
this._markerGroup.removeLayer(lastMarker);
if (latlngs.length < 2) {
this._map.removeLayer(poly);
}
this._vertexChanged(latlng, false);
},
// @method addVertex(): void
// Add a vertex to the end of the polyline
addVertex: function (latlng) {
var markersLength = this._markers.length;
// markersLength must be greater than or equal to 2 before intersections can occur
if (markersLength >= 2 && !this.options.allowIntersection && this._poly.newLatLngIntersects(latlng)) {
this._showErrorTooltip();
return;
} else if (this._errorShown) {
this._hideErrorTooltip();
}
this._markers.push(this._createMarker(latlng));
this._poly.addLatLng(latlng);
if (this._poly.getLatLngs().length === 2) {
this._map.addLayer(this._poly);
}
this._vertexChanged(latlng, true);
},
// @method completeShape(): void
// Closes the polyline between the first and last points
completeShape: function () {
if (this._markers.length <= 1 || !this._shapeIsValid()) {
return;
}
this._fireCreatedEvent();
this.disable();
if (this.options.repeatMode) {
this.enable();
}
},
_finishShape: function () {
var latlngs = this._poly.getLatLngs();
var intersects = this._poly.newLatLngIntersects(latlngs[latlngs.length - 1]);
if ((!this.options.allowIntersection && intersects) || !this._shapeIsValid()) {
this._showErrorTooltip();
return;
}
this._fireCreatedEvent();
this.disable();
if (this.options.repeatMode) {
this.enable();
}
},
// Called to verify the shape is valid when the user tries to finish it
// Return false if the shape is not valid
_shapeIsValid: function () {
return true;
},
_onZoomEnd: function () {
if (this._markers !== null) {
this._updateGuide();
}
},
_onMouseMove: function (e) {
var newPos = this._map.mouseEventToLayerPoint(e.originalEvent);
var latlng = this._map.layerPointToLatLng(newPos);
// Save latlng
// should this be moved to _updateGuide() ?
this._currentLatLng = latlng;
this._updateTooltip(latlng);
// Update the guide line
this._updateGuide(latlng);
// Update the mouse marker position
this._mouseMarker.setLatLng(latlng);
L.DomEvent.preventDefault(e.originalEvent);
},
_vertexChanged: function (latlng, added) {
this._map.fire(L.Draw.Event.DRAWVERTEX, {layers: this._markerGroup});
this._updateFinishHandler();
this._updateRunningMeasure(latlng, added);
this._clearGuides();
this._updateTooltip();
},
_onMouseDown: function (e) {
if (this._shouldAbortMouseEvent.call(this, e))
return;
if (!this._clickHandled && !this._touchHandled && !this._disableMarkers) {
this._onMouseMove(e);
this._clickHandled = true;
this._disableNewMarkers();
var originalEvent = e.originalEvent;
var clientX = originalEvent.clientX;
var clientY = originalEvent.clientY;
this._startPoint.call(this, clientX, clientY, e);
}
},
_shouldAbortMouseEvent: function (e) {
let {lat, lng} = e.latlng;
return !this.options.shapeOptions.naturalDrawing && (lat > 85 || lat < -85 || lng < -180 || lng > 180);
},
_startPoint: function (clientX, clientY) {
this._mouseDownOrigin = L.point(clientX, clientY);
},
_onMouseUp: function (e) {
if (this._shouldAbortMouseEvent.call(this, e))
return;
var originalEvent = e.originalEvent;
var clientX = originalEvent.clientX;
var clientY = originalEvent.clientY;
this._endPoint.call(this, clientX, clientY, e);
this._clickHandled = null;
},
_endPoint: function (clientX, clientY, e) {
if (this._mouseDownOrigin) {
var dragCheckDistance = L.point(clientX, clientY)
.distanceTo(this._mouseDownOrigin);
var lastPtDistance = this._calculateFinishDistance(e.latlng);
if (this.options.maxPoints > 1 && this.options.maxPoints === this._markers.length + 1) {
this.addVertex(e.latlng);
this._finishShape();
} else if (lastPtDistance < 10 && L.Browser.touch) {
this._finishShape();
} else if (Math.abs(dragCheckDistance) < 9 * (window.devicePixelRatio || 1)) {
this.addVertex(e.latlng);
}
this._enableNewMarkers(); // after a short pause, enable new markers
}
this._mouseDownOrigin = null;
},
// ontouch prevented by clickHandled flag because some browsers fire both click/touch events,
// causing unwanted behavior
_onTouch: function (e) {
if (this._shouldAbortMouseEvent.call(this, e))
return;
var originalEvent = e.originalEvent;
var clientX;
var clientY;
if (originalEvent.touches && originalEvent.touches[0] && !this._clickHandled && !this._touchHandled && !this._disableMarkers) {
clientX = originalEvent.touches[0].clientX;
clientY = originalEvent.touches[0].clientY;
this._disableNewMarkers();
this._touchHandled = true;
this._startPoint.call(this, clientX, clientY, e);
this._endPoint.call(this, clientX, clientY, e);
this._touchHandled = null;
}
this._clickHandled = null;
},
_onMouseOut: function () {
if (this._tooltip) {
this._tooltip._onMouseOut.call(this._tooltip);
}
},
// calculate if we are currently within close enough distance
// of the closing point (first point for shapes, last point for lines)
// this is semi-ugly code but the only reliable way i found to get the job done
// note: calculating point.distanceTo between mouseDownOrigin and last marker did NOT work
_calculateFinishDistance: function (potentialLatLng) {
var lastPtDistance;
if (this._markers.length > 0) {
var finishMarker;
if (this.type === L.Draw.Polyline.TYPE) {
finishMarker = this._markers[this._markers.length - 1];
} else if (this.type === L.Draw.Polygon.TYPE) {
finishMarker = this._markers[0];
} else {
return Infinity;
}
var lastMarkerPoint = this._map.latLngToContainerPoint(finishMarker.getLatLng()),
potentialMarker = new L.Marker(potentialLatLng, {
icon: this.options.icon,
zIndexOffset: this.options.zIndexOffset * 2
});
var potentialMarkerPint = this._map.latLngToContainerPoint(potentialMarker.getLatLng());
lastPtDistance = lastMarkerPoint.distanceTo(potentialMarkerPint);
} else {
lastPtDistance = Infinity;
}
return lastPtDistance;
},
_updateFinishHandler: function () {
var markerCount = this._markers.length;
// The last marker should have a click handler to close the polyline
if (markerCount > 1) {
this._markers[markerCount - 1].on('click', this._finishShape, this);
}
// Remove the old marker click handler (as only the last point should close the polyline)
if (markerCount > 2) {
this._markers[markerCount - 2].off('click', this._finishShape, this);
}
},
_createMarker: function (latlng) {
var marker = new L.Marker(latlng, {
icon: this.options.icon,
zIndexOffset: this.options.zIndexOffset * 2
});
this._markerGroup.addLayer(marker);
return marker;
},
_updateGuide: function (newPos) {
var markerCount = this._markers ? this._markers.length : 0;
if (markerCount > 0) {
newPos = newPos || this._currentLatLng;
// draw the guide line
//this._clearGuides();
this._drawGuide(this._markers[markerCount - 1].getLatLng(), newPos);
}
},
_updateTooltip: function (latLng) {
var text = this._getTooltipText();
if (latLng) {
this._tooltip.updatePosition(latLng);
}
if (!this._errorShown) {
this._tooltip.updateContent(text);
}
},
_drawGuide: function (pointA, pointB) {
this.guideLine.addTo(this._map);
this.guideLine.setLatLngs([pointA, pointB]);
},
_updateGuideColor: function (color) {
this.guideLine.setStyle({color});
},
// removes all child elements (guide dashes) from the guides container
_clearGuides: function () {
this.guideLine.remove();
},
_getTooltipText: function () {
var showLength = this.options.showLength,
labelText, distanceStr;
if (this._markers.length === 0) {
labelText = {
text: L.drawLocal.draw.handlers.polyline.tooltip.start
};
} else {
distanceStr = showLength ? this._getMeasurementString() : '';
if (this._markers.length === 1) {
labelText = {
text: L.drawLocal.draw.handlers.polyline.tooltip.cont,
subtext: distanceStr
};
} else {
labelText = {
text: L.drawLocal.draw.handlers.polyline.tooltip.end,
subtext: distanceStr
};
}
}
return labelText;
},
_updateRunningMeasure: function (latlng, added) {
var markersLength = this._markers.length,
previousMarkerIndex, distance;
if (this._markers.length === 1) {
this._measurementRunningTotal = 0;
} else {
previousMarkerIndex = markersLength - (added ? 2 : 1);
// Calculate the distance based on the version
if (L.GeometryUtil.isVersion07x()) {
distance = latlng.distanceTo(this._markers[previousMarkerIndex].getLatLng()) * (this.options.factor || 1);
} else {
distance = this._map.distance(latlng, this._markers[previousMarkerIndex].getLatLng()) * (this.options.factor || 1);
}
this._measurementRunningTotal += distance * (added ? 1 : -1);
}
},
_getMeasurementString: function () {
var currentLatLng = this._currentLatLng,
previousLatLng = this._markers[this._markers.length - 1].getLatLng(),
distance;
// Calculate the distance from the last fixed point to the mouse position based on the version
if (L.GeometryUtil.isVersion07x()) {
distance = previousLatLng && currentLatLng && currentLatLng.distanceTo ? this._measurementRunningTotal + currentLatLng.distanceTo(previousLatLng) * (this.options.factor || 1) : this._measurementRunningTotal || 0;
} else {
distance = previousLatLng && currentLatLng ? this._measurementRunningTotal + this._map.distance(currentLatLng, previousLatLng) * (this.options.factor || 1) : this._measurementRunningTotal || 0;
}
return L.GeometryUtil.readableDistance(distance, this.options.metric, this.options.feet, this.options.nautic, this.options.precision);
},
_showErrorTooltip: function () {
this._errorShown = true;
// Update tooltip
this._tooltip
.showAsError()
.updateContent({text: this.options.drawError.message});
// Update shape
this._updateGuideColor(this.options.drawError.color);
this._poly.setStyle({color: this.options.drawError.color});
// Hide the error after 2 seconds
this._clearHideErrorTimeout();
this._hideErrorTimeout = setTimeout(L.Util.bind(this._hideErrorTooltip, this), this.options.drawError.timeout);
},
_hideErrorTooltip: function () {
this._errorShown = false;
this._clearHideErrorTimeout();
// Revert tooltip
this._tooltip
.removeError()
.updateContent(this._getTooltipText());
// Revert shape
this._updateGuideColor(this.options.shapeOptions.color);
this._poly.setStyle({color: this.options.shapeOptions.color});
},
_clearHideErrorTimeout: function () {
if (this._hideErrorTimeout) {
clearTimeout(this._hideErrorTimeout);
this._hideErrorTimeout = null;
}
},
// disable new markers temporarily;
// this is to prevent duplicated touch/click events in some browsers
_disableNewMarkers: function () {
this._disableMarkers = true;
},
// see _disableNewMarkers
_enableNewMarkers: function () {
setTimeout(function () {
this._disableMarkers = false;
}.bind(this), 50);
},
_cleanUpShape: function () {
if (this._markers.length > 1) {
this._markers[this._markers.length - 1].off('click', this._finishShape, this);
}
},
_fireCreatedEvent: function () {
let coords = this._poly.getLatLngs(), poly;
if (this._poly instanceof L.Geodesic)
poly = _createGeodesic(coords, this.options.shapeOptions)
else
poly = new this.Poly(coords, this.options.shapeOptions);
L.Draw.Feature.prototype._fireCreatedEvent.call(this, poly);
}
});
// Edit handler
/**
* @class L.Edit.Polyline
* @aka L.Edit.Poly
* @aka Edit.Poly
*/
L.Edit.Poly = L.Handler.extend({
// @method initialize(): void
initialize: function (poly) {
this.latlngs = [poly.getLatLngs()];
if (poly._holes) {
this.latlngs = this.latlngs.concat(poly._holes);
}
this._poly = poly;
this._poly.on('revert-edited', this._updateLatLngs, this);
},
// Compatibility method to normalize Poly* objects
// between 0.7.x and 1.0+
_defaultShape: function () {
let latLngs = this._poly.getLatLngs();
if (!L.Polyline._flat)
return latLngs;
return L.Polyline._flat(latLngs) ? latLngs : latLngs[0];
},
_eachVertexHandler: function (callback) {
for (var i = 0; i < this._verticesHandlers.length; i++) {
callback(this._verticesHandlers[i]);
}
},
// @method addHooks(): void
// Add listener hooks to this handler
addHooks: function () {
this._initHandlers();
this._eachVertexHandler(function (handler) {
handler.addHooks();
});
},
// @method removeHooks(): void
// Remove listener hooks from this handler
removeHooks: function () {
this._eachVertexHandler(function (handler) {
handler.removeHooks();
});
},
// @method updateMarkers(): void
// Fire an update for each vertex handler
updateMarkers: function () {
this._eachVertexHandler(function (handler) {
handler.updateMarkers();
});
},
_initHandlers: function () {
this._verticesHandlers = [];
for (var i = 0; i < this.latlngs.length; i++) {
this._verticesHandlers.push(new L.Edit.PolyVerticesEdit(this._poly, this.latlngs[i], this._poly.options.poly));
}
},
_updateLatLngs: function (e) {
this.latlngs = [e.layer.getLatLngs()];
if (e.layer._holes) {
this.latlngs = this.latlngs.concat(e.layer._holes);
}
}
});
/**
* @class L.Edit.PolyVerticesEdit
* @aka Edit.PolyVerticesEdit
*/
L.Edit.PolyVerticesEdit = L.Handler.extend({
options: {
icon: new L.DivIcon({
iconSize: new L.Point(8, 8),
className: 'leaflet-div-icon leaflet-editing-icon'
}),
touchIcon: new L.DivIcon({
iconSize: new L.Point(20, 20),
className: 'leaflet-div-icon leaflet-editing-icon leaflet-touch-icon'
}),
drawError: {
color: '#b00b00',
timeout: 1000
}
},
// @method intialize(): void
initialize: function (poly, latlngs, options) {
// if touch, switch to touch icon
if (L.Browser.touch) {
this.options.icon = this.options.touchIcon;
}
this._poly = poly;
if (options && options.drawError) {
options.drawError = L.Util.extend({}, this.options.drawError, options.drawError);
}
L.setOptions(this, options);
},
// Compatibility method to normalize Poly* objects
// between 0.7.x and 1.0+
_defaultShape: function () {
let latLngs = this._poly.getLatLngs();
if (!L.Polyline._flat) {
return latLngs;
}
return L.Polyline._flat(latLngs) ? latLngs : latLngs[0];
},
// @method addHooks(): void
// Add listener hooks to this handler.
addHooks: function () {
var poly = this._poly;
var path = poly._path;
if (!(poly instanceof L.Polygon)) {
poly.options.fill = false;
if (poly.options.editing) {
poly.options.editing.fill = false;
}
}
if (path) {
if (poly.options.editing && poly.options.editing.className) {
if (poly.options.original.className) {
poly.options.original.className.split(' ').forEach(function (className) {
L.DomUtil.removeClass(path, className);
});
}
poly.options.editing.className.split(' ').forEach(function (className) {
L.DomUtil.addClass(path, className);
});
}
}
poly.setStyle(poly.options.editing);
if (this._poly._map) {
this._map = this._poly._map; // Set map
if (!this._markerGroup) {
this._initMarkers();
}
this._poly._map.addLayer(this._markerGroup);
}
},
// @method removeHooks(): void
// Remove listener hooks from this handler.
removeHooks: function () {
var poly = this._poly;
var path = poly._path;
if (path) {
if (poly.options.editing && poly.options.editing.className) {
poly.options.editing.className.split(' ').forEach(function (className) {
L.DomUtil.removeClass(path, className);
});
if (poly.options.original.className) {
poly.options.original.className.split(' ').forEach(function (className) {
L.DomUtil.addClass(path, className);
});
}
}
}
poly.setStyle(poly.options.original);
if (poly._map) {
poly._map.removeLayer(this._markerGroup);
delete this._markerGroup;
delete this._markers;
}
},
// @method updateMarkers(): void
// Clear markers and update their location
updateMarkers: function () {
this._markerGroup.clearLayers();
this._initMarkers();
},
_initMarkers: function () {
if (!this._markerGroup) {
this._markerGroup = new L.LayerGroup();
}
this._markers = [];
var latlngs = this._defaultShape(),
i, j, len, marker;
for (i = 0, len = latlngs.length; i < len; i++) {
marker = this._createMarker(latlngs[i], i);
marker.on('click', this._onMarkerClick, this);
marker.on('contextmenu', this._onContextMenu, this);
this._markers.push(marker);
}
var markerLeft, markerRight;
for (i = 0, j = len - 1; i < len; j = i++) {
if (i === 0 && !(L.Polygon && (this._poly instanceof L.Polygon))) {
continue;
}
markerLeft = this._markers[j];
markerRight = this._markers[i];
this._createMiddleMarker(markerLeft, markerRight);
this._updatePrevNext(markerLeft, markerRight);
}
},
_createMarker: function (latlng, index) {
// Extending L.Marker in TouchEvents.js to include touch.
var marker = new L.Marker.Touch(latlng, {
draggable: true,
icon: this.options.icon,
});
marker._origLatLng = latlng;
marker._index = index;
marker
.on('dragstart', this._onMarkerDragStart, this)
.on('drag', this._onMarkerDrag, this)
.on('dragend', this._fireEdit, this)
.on('touchmove', this._onTouchMove, this)
.on('touchend', this._fireEdit, this)
.on('MSPointerMove', this._onTouchMove, this)
.on('MSPointerUp', this._fireEdit, this);
this._markerGroup.addLayer(marker);
return marker;
},
_onMarkerDragStart: function () {
this._poly.fire('editstart');
},
_spliceLatLngs: function () {
var latlngs = this._defaultShape();
var removed = [].splice.apply(latlngs, arguments);
this._poly._convertLatLngs(latlngs, true);
L.redrawLayer(this._poly);
return removed;
},
_removeMarker: function (marker) {
var i = marker._index;
this._markerGroup.removeLayer(marker);
this._markers.splice(i, 1);
this._spliceLatLngs(i, 1);
this._updateIndexes(i, -1);
marker
.off('dragstart', this._onMarkerDragStart, this)
.off('drag', this._onMarkerDrag, this)
.off('dragend', this._fireEdit, this)
.off('touchmove', this._onMarkerDrag, this)
.off('touchend', this._fireEdit, this)
.off('click', this._onMarkerClick, this)
.off('MSPointerMove', this._onTouchMove, this)
.off('MSPointerUp', this._fireEdit, this);
},
_fireEdit: function () {
this._poly.edited = true;
this._poly.fire('edit');
this._poly._map.fire(L.Draw.Event.EDITVERTEX, {layers: this._markerGroup, poly: this._poly});
},
_onMarkerDrag: function (e) {
var marker = e.target;
var poly = this._poly;
var oldOrigLatLng = L.LatLngUtil.cloneLatLng(marker._origLatLng);
L.extend(marker._origLatLng, marker._latlng);
if (poly.options.poly) {
var tooltip = poly._map._editTooltip; // Access the tooltip
// If we don't allow intersections and the polygon intersects
if (!poly.options.poly.allowIntersection && poly.intersects()) {
L.extend(marker._origLatLng, oldOrigLatLng);
marker.setLatLng(oldOrigLatLng);
var originalColor = poly.options.color;
poly.setStyle({color: this.options.drawError.color});
if (tooltip) {
tooltip.updateContent({
text: L.drawLocal.draw.handlers.polyline.error
});
}
// Reset everything back to normal after a second
setTimeout(function () {
poly.setStyle({color: originalColor});
if (tooltip) {
tooltip.updateContent({
text: L.drawLocal.edit.handlers.edit.tooltip.text,
subtext: L.drawLocal.edit.handlers.edit.tooltip.subtext
});
}
}, 1000);
}
}
if (marker._middleLeft) {
marker._middleLeft.setLatLng(this._getMiddleLatLng(marker._prev, marker));
}
if (marker._middleRight) {
marker._middleRight.setLatLng(this._getMiddleLatLng(marker, marker._next));
}
//refresh the bounds when draging
this._poly._bounds._southWest = L.latLng(Infinity, Infinity);
this._poly._bounds._northEast = L.latLng(-Infinity, -Infinity);
var latlngs = this._poly.getLatLngs();
this._poly._convertLatLngs(latlngs, true);
L.redrawLayer(this._poly);
this._poly.fire('editdrag');
},
_onMarkerClick: function (e) {
var minPoints = L.Polygon && (this._poly instanceof L.Polygon) ? 4 : 3,
marker = e.target;
// If removing this point would create an invalid polyline/polygon don't remove
if (this._defaultShape().length < minPoints) {
return;
}
// remove the marker
this._removeMarker(marker);
// update prev/next links of adjacent markers
this._updatePrevNext(marker._prev, marker._next);
// remove ghost markers near the removed marker
if (marker._middleLeft) {
this._markerGroup.removeLayer(marker._middleLeft);
}
if (marker._middleRight) {
this._markerGroup.removeLayer(marker._middleRight);
}
// create a ghost marker in place of the removed one
if (marker._prev && marker._next) {
this._createMiddleMarker(marker._prev, marker._next);
} else if (!marker._prev) {
marker._next._middleLeft = null;
} else if (!marker._next) {
marker._prev._middleRight = null;
}
this._fireEdit();
},
_onContextMenu: function (e) {
var marker = e.target;
this._poly._map.fire(L.Draw.Event.MARKERCONTEXT, {marker: marker, layers: this._markerGroup, poly: this._poly});
L.DomEvent.stopPropagation;
},
_onTouchMove: function (e) {
var layerPoint = this._map.mouseEventToLayerPoint(e.originalEvent.touches[0]),
latlng = this._map.layerPointToLatLng(layerPoint),
marker = e.target;
L.extend(marker._origLatLng, latlng);
if (marker._middleLeft) {