-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leaflet.PolylineMeasure.js
1489 lines (1421 loc) · 78.4 KB
/
Leaflet.PolylineMeasure.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
/*********************************************************
** **
** Leaflet Plugin "Leaflet.PolylineMeasure" **
** File "Leaflet.PolylineMeasure.js" **
** Date: 2022-10-07 **
** **
*********************************************************/
/* NOTE: This is not the original version. It was modified to be used on microchips instead of
* planet Earth itself:
*
* -> Makes straight lines instead of arcs.
* -> Distances are calculated in milli-, micro- and nanometers.
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['leaflet'], factory);
} else if (typeof module !== 'undefined') {
// Node/CommonJS
module.exports = factory(require('leaflet'));
} else {
// Browser globals
if (typeof window.L === 'undefined') {
throw new Error('Leaflet must be loaded first');
}
factory(window.L);
}
}(function (L) {
var _measureControlId = 'polyline-measure-control';
var _unicodeClass = 'polyline-measure-unicode-icon';
/**
* Polyline Measure class
* @extends L.Control
*/
L.Control.PolylineMeasure = L.Control.extend({
/**
* Default options for the tool
* @type {Object}
*/
options: {
/**
* Position to show the control. Possible values are: 'topright', 'topleft', 'bottomright', 'bottomleft'
* @type {String}
* @default
*/
position: 'topleft',
/**
* Default unit the distances are displayed in. Possible values are: 'millimeters'
* @type {String}
* @default
*/
unit: 'millimeters',
/**
* Use subunits (micrometers, nanometers) in tooltips in case of distances less then 1 millimeter
* @type {Boolean}
* @default
*/
useSubunits: true,
/**
* Clear all measurements when Measure Control is switched off
* @type {Boolean}
* @default
*/
clearMeasurementsOnStop: true,
/**
* Whether bearings are displayed within the tooltips
* @type {Boolean}
* @default
*/
showBearings: false,
/**
* Text for the bearing In
* @type {String}
* @default
*/
bearingTextIn: 'In',
/**
* Text for the bearing Out
* @type {String}
* @default
*/
bearingTextOut: 'Out',
/**
* Text for last point's tooltip
* @type {String}
* @default
*/
tooltipTextFinish: 'Click to <b>finish line</b><br>',
tooltipTextDelete: 'Press SHIFT-key and click to <b>delete point</b>',
tooltipTextMove: 'Click and drag to <b>move point</b><br>',
tooltipTextResume: '<br>Press CTRL-key and click to <b>resume line</b>',
tooltipTextAdd: 'Press CTRL-key and click to <b>add point</b>',
/**
* Title for the control going to be switched on
* @type {String}
* @default
*/
measureControlTitleOn: "Turn on PolylineMeasure",
/**
* Title for the control going to be switched off
* @type {String}
* @default
*/
measureControlTitleOff: "Turn off PolylineMeasure",
/**
* Label of the Measure control (maybe a unicode symbol)
* @type {String}
* @default
*/
measureControlLabel: '↦',
/**
* Classes to apply to the Measure control
* @type {Array}
* @default
*/
measureControlClasses: [],
/**
* Show a control to clear all the measurements
* @type {Boolean}
* @default
*/
showClearControl: false,
/**
* Title text to show on the Clear measurements control button
* @type {String}
* @default
*/
clearControlTitle: 'Clear Measurements',
/**
* Label of the Clear control (maybe a unicode symbol)
* @type {String}
* @default
*/
clearControlLabel: '×',
/**
* Classes to apply to Clear control button
* @type {Array}
* @default
*/
clearControlClasses: [],
/**
* Show a control to change the units of measurements
* @type {Boolean}
* @default
*/
showUnitControl: false,
/**
* The measurement units that can be cycled through by using the Unit Control button
* @type {Array}
* @default
*/
unitControlUnits: ["millimeters"],
/**
* Title texts to show on the Unit Control button
* @type {Object}
* @default
*/
unitControlTitle: {
text: 'Change Units',
nanometers: 'millimeters',
},
/**
* Unit symbols to show in the Unit Control button and measurement labels
* @type {Object}
* @default
*/
unitControlLabel: {
millimeters: 'mm',
micrometers: 'µm',
nanometers: 'nm',
},
/**
* Classes to apply to the Unit control
* @type {Array}
* @default
*/
unitControlClasses: [],
/**
* Styling settings for the temporary dashed rubberline
* @type {Object}
*/
tempLine: {
/**
* Dashed line color
* @type {String}
* @default
*/
color: '#00f',
/**
* Dashed line weight
* @type {Number}
* @default
*/
weight: 2
},
/**
* Styling for the fixed polyline
* @type {Object}
*/
fixedLine: {
/**
* Solid line color
* @type {String}
* @default
*/
color: '#006',
/**
* Solid line weight
* @type {Number}
* @default
*/
weight: 2
},
/**
* Styling of the midway arrow
* @type {Object}
*/
arrow: {
/**
* Color of the arrow
* @type {String}
* @default
*/
color: '#000'
},
/**
* Style settings for circle marker indicating the starting point of the polyline
* @type {Object}
*/
startCircle: {
/**
* Color of the border of the circle
* @type {String}
* @default
*/
color: '#000',
/**
* Weight of the circle
* @type {Number}
* @default
*/
weight: 1,
/**
* Fill color of the circle
* @type {String}
* @default
*/
fillColor: '#0f0',
/**
* Fill opacity of the circle
* @type {Number}
* @default
*/
fillOpacity: 1,
/**
* Radius of the circle
* @type {Number}
* @default
*/
radius: 3
},
/**
* Style settings for all circle markers between startCircle and endCircle
* @type {Object}
*/
intermedCircle: {
/**
* Color of the border of the circle
* @type {String}
* @default
*/
color: '#000',
/**
* Weight of the circle
* @type {Number}
* @default
*/
weight: 1,
/**
* Fill color of the circle
* @type {String}
* @default
*/
fillColor: '#ff0',
/**
* Fill opacity of the circle
* @type {Number}
* @default
*/
fillOpacity: 1,
/**
* Radius of the circle
* @type {Number}
* @default
*/
radius: 3
},
/**
* Style settings for circle marker indicating the latest point of the polyline during drawing a line
* @type {Object}
*/
currentCircle: {
/**
* Color of the border of the circle
* @type {String}
* @default
*/
color: '#000',
/**
* Weight of the circle
* @type {Number}
* @default
*/
weight: 1,
/**
* Fill color of the circle
* @type {String}
* @default
*/
fillColor: '#f0f',
/**
* Fill opacity of the circle
* @type {Number}
* @default
*/
fillOpacity: 1,
/**
* Radius of the circle
* @type {Number}
* @default
*/
radius: 6
},
/**
* Style settings for circle marker indicating the end point of the polyline
* @type {Object}
*/
endCircle: {
/**
* Color of the border of the circle
* @type {String}
* @default
*/
color: '#000',
/**
* Weight of the circle
* @type {Number}
* @default
*/
weight: 1,
/**
* Fill color of the circle
* @type {String}
* @default
*/
fillColor: '#f00',
/**
* Fill opacity of the circle
* @type {Number}
* @default
*/
fillOpacity: 1,
/**
* Radius of the circle
* @type {Number}
* @default
*/
radius: 3
}
},
_arcpoints: 2, // 2 points = 1 line segment. lower value to make arc less accurate or increase value to make it more accurate.
_circleNr: -1,
_lineNr: -1,
/**
* Create a control button
* @param {String} label Label to add
* @param {String} title Title to show on hover
* @param {Array} classesToAdd Collection of classes to add
* @param {Element} container Parent element
* @param {Function} fn Callback function to run
* @param {Object} context Context
* @returns {Element} Created element
* @private
*/
_createControl: function (label, title, classesToAdd, container, fn, context) {
var anchor = document.createElement('a');
anchor.innerHTML = label;
anchor.setAttribute('title', title);
classesToAdd.forEach(function(c) {
anchor.classList.add(c);
});
L.DomEvent.on (anchor, 'click', fn, context);
container.appendChild(anchor);
return anchor;
},
/**
* Method to fire on add to map
* @param {Object} map Map object
* @returns {Element} Containing element
*/
onAdd: function(map) {
var self = this
// needed to avoid creating points by mouseclick during dragging the map
map.on('movestart ', function() {
self._mapdragging = true
})
this._container = document.createElement('div');
this._container.classList.add('leaflet-bar');
L.DomEvent.disableClickPropagation(this._container); // otherwise drawing process would instantly start at controls' container or double click would zoom-in map
var title = this.options.measureControlTitleOn;
var label = this.options.measureControlLabel;
var classes = this.options.measureControlClasses;
if (label.indexOf('&') != -1) {
classes.push(_unicodeClass);
}
// initialize state
this._arrPolylines = [];
this._measureControl = this._createControl (label, title, classes, this._container, this._toggleMeasure, this);
this._defaultControlBgColor = this._measureControl.style.backgroundColor;
this._measureControl.setAttribute('id', _measureControlId);
if (this.options.showClearControl) {
var title = this.options.clearControlTitle;
var label = this.options.clearControlLabel;
var classes = this.options.clearControlClasses;
if (label.indexOf('&') != -1) {
classes.push(_unicodeClass);
}
this._clearMeasureControl = this._createControl (label, title, classes, this._container, this._clearAllMeasurements, this);
this._clearMeasureControl.classList.add('polyline-measure-clearControl')
}
// There is no point in using the unitControl if there are no units to choose from.
if (this.options.showUnitControl && this.options.unitControlUnits.length > 1) {
var label = this.options.unitControlLabel[this.options.unit];
var title = this.options.unitControlTitle.text + " [" + this.options.unitControlTitle[this.options.unit] + "]";
var classes = this.options.unitControlClasses;
this._unitControl = this._createControl (label, title, classes, this._container, this._changeUnit, this);
this._unitControl.setAttribute ('id', 'unitControlId');
}
return this._container;
},
/**
* Method to fire on remove from map
*/
onRemove: function () {
if (this._measuring) {
this._toggleMeasure();
}
},
// turn off all Leaflet-own events of markers (popups, tooltips). Needed to allow creating points on top of markers
_saveNonpolylineEvents: function () {
this._nonpolylineTargets = this._map._targets;
if (typeof this._polylineTargets !== 'undefined') {
this._map._targets = this._polylineTargets;
} else {
this._map._targets ={};
}
},
// on disabling the measure add-on, save Polyline-measure events and enable the former Leaflet-own events again
_savePolylineEvents: function () {
this._polylineTargets = this._map._targets;
this._map._targets = this._nonpolylineTargets;
},
/**
* Toggle the measure functionality on or off
* @private
*/
_toggleMeasure: function () {
this._measuring = !this._measuring;
if (this._measuring) { // if measuring is going to be switched on
this._mapdragging = false;
this._saveNonpolylineEvents ();
this._measureControl.classList.add ('polyline-measure-controlOnBgColor');
this._measureControl.style.backgroundColor = this.options.backgroundColor;
this._measureControl.title = this.options.measureControlTitleOff;
this._oldCursor = this._map._container.style.cursor; // save former cursor type
this._map._container.style.cursor = 'crosshair';
this._doubleClickZoom = this._map.doubleClickZoom.enabled(); // save former status of doubleClickZoom
this._map.doubleClickZoom.disable();
// create LayerGroup "layerPaint" (only) the first time Measure Control is switched on
if (!this._layerPaint) {
this._layerPaint = L.layerGroup().addTo(this._map);
}
this._map.on ('mousemove', this._mouseMove, this); // enable listing to 'mousemove', 'click', 'keydown' events
this._map.on ('click', this._mouseClick, this);
L.DomEvent.on (document, 'keydown', this._onKeyDown, this);
this._resetPathVariables();
} else { // if measuring is going to be switched off
this._savePolylineEvents ();
this._measureControl.classList.remove ('polyline-measure-controlOnBgColor');
this._measureControl.style.backgroundColor = this._defaultControlBgColor;
this._measureControl.title = this.options.measureControlTitleOn;
this._map._container.style.cursor = this._oldCursor;
this._map.off ('mousemove', this._mouseMove, this);
this._map.off ('click', this._mouseClick, this);
this._map.off ('mousemove', this._resumeFirstpointMousemove, this);
this._map.off ('click', this._resumeFirstpointClick, this);
this._map.off ('mousemove', this._dragCircleMousemove, this);
this._map.off ('mouseup', this._dragCircleMouseup, this);
L.DomEvent.off (document, 'keydown', this._onKeyDown, this);
if(this._doubleClickZoom) {
this._map.doubleClickZoom.enable();
}
if(this.options.clearMeasurementsOnStop && this._layerPaint) {
this._clearAllMeasurements();
}
// to remove temp. Line if line at the moment is being drawn and not finished while clicking the control
if (this._cntCircle !== 0) {
this._finishPolylinePath();
}
}
// allow easy to connect the measure control to the app, f.e. to disable the selection on the map when the measurement is turned on
this._map.fire('polylinemeasure:toggle', { status: this._measuring });
},
/**
* Clear all measurements from the map
*/
_clearAllMeasurements: function() {
if ((this._cntCircle !== undefined) && (this._cntCircle !== 0)) {
this._finishPolylinePath();
}
if (this._layerPaint) {
this._layerPaint.clearLayers();
}
this._arrPolylines = [];
this._map.fire('polylinemeasure:clear');
},
_changeUnit: function() {
// Retrieve the index of the next available unit of measurement.
let indexCurrUnit = this.options.unitControlUnits.indexOf(this.options.unit);
let indexNextUnit = (indexCurrUnit+1)%this.options.unitControlUnits.length;
// Update the unit of measurement.
this.options.unit = this.options.unitControlUnits[indexNextUnit];
this._unitControl.innerHTML = this.options.unitControlLabel[this.options.unit];
this._unitControl.title = this.options.unitControlTitle.text +" [" + this.options.unitControlTitle[this.options.unit] + "]";
if (this._currentLine) {
this._computeDistance(this._currentLine);
}
this._arrPolylines.map (this._computeDistance.bind(this));
},
_computeDistance: function(line) {
var totalDistance = 0;
line.circleCoords.map (function(point, point_index) {
if (point_index >= 1) {
var distance = line.circleCoords [point_index - 1].distanceTo (line.circleCoords [point_index]);
totalDistance += distance;
this._updateTooltip (line.tooltips [point_index], line.tooltips [point_index - 1], totalDistance, distance, line.circleCoords [point_index - 1], line.circleCoords [point_index]);
}
}.bind(this));
},
/**
* Event to fire when a keyboard key is depressed.
* Currently only watching for ESC key (= keyCode 27). 1st press finishes line, 2nd press turns Measuring off.
* @param {Object} e Event
* @private
*/
_onKeyDown: function (e) {
if (e.keyCode === 27) {
// if resuming a line at its first point is active
if (this._resumeFirstpointFlag === true) {
this._resumeFirstpointFlag = false;
var lineNr = this._lineNr;
this._map.off ('mousemove', this._resumeFirstpointMousemove, this);
this._map.off ('click', this._resumeFirstpointClick, this);
this._layerPaint.removeLayer (this._rubberlinePath2);
this._layerPaint.removeLayer (this._tooltipNew);
this._arrPolylines[lineNr].circleMarkers [0].setStyle (this.options.startCircle);
var text = '';
var totalDistance = 0;
if (this.options.showBearings === true) {
text = this.options.bearingTextIn+':---°<br>'+this.options.bearingTextOut+':---°';
}
text = text + '<div class="polyline-measure-tooltip-difference">+' + '0</div>';
text = text + '<div class="polyline-measure-tooltip-total">' + '0</div>';
this._arrPolylines[lineNr].tooltips [0]._icon.innerHTML = text;
this._arrPolylines[lineNr].tooltips.map (function (item, index) {
if (index >= 1) {
var distance = this._arrPolylines[lineNr].circleCoords[index-1].distanceTo (this._arrPolylines[lineNr].circleCoords[index]);
var lastCircleCoords = this._arrPolylines[lineNr].circleCoords[index - 1];
var mouseCoords = this._arrPolylines[lineNr].circleCoords[index];
totalDistance += distance;
var prevTooltip = this._arrPolylines[lineNr].tooltips[index-1]
this._updateTooltip (item, prevTooltip, totalDistance, distance, lastCircleCoords, mouseCoords);
}
}.bind (this));
this._map.on ('mousemove', this._mouseMove, this);
return
}
if (!this._currentLine) { // if NOT drawing a line, ESC will directly switch of measuring
this._toggleMeasure();
} else { // if drawing a line, ESC will finish the current line
this._finishPolylinePath(e);
}
}
},
/**
* Get the distance in the format specified in the options
* @param {Number} distance Distance to convert
* @returns {{value: *, unit: *}}
* @private
*/
_getDistance: function (distance) {
var dist = distance;
var unit = this.options.unitControlLabel.millimeters;
if (dist >= 1000000) {
dist = (dist/1000000).toFixed(6);
} else {
if (!this.options.useSubunits) {
dist = (dist/1000000).toFixed(6);
} else {
if (dist >= 1000) {
dist = (dist/1000).toFixed(3);
unit = this.options.unitControlLabel.micrometers;
} else {
dist = (dist).toFixed(0);
unit = this.options.unitControlLabel.nanometers;
}
}
}
return {value:dist, unit:unit};
},
/**
* Calculate Great-circle Arc (= shortest distance on a sphere like the Earth) between two coordinates
* formulas: http://www.edwilliams.org/avform.htm
* @private
*/
_polylineArc: function (_from, _to) {
function _GCinterpolate (f) {
var A = Math.sin((1 - f) * d) / Math.sin(d);
var B = Math.sin(f * d) / Math.sin(d);
var x = A * Math.cos(fromLat) * Math.cos(fromLng) + B * Math.cos(toLat) * Math.cos(toLng);
var y = A * Math.cos(fromLat) * Math.sin(fromLng) + B * Math.cos(toLat) * Math.sin(toLng);
var z = A * Math.sin(fromLat) + B * Math.sin(toLat);
// atan2 better than atan-function cause results are from -pi to +pi
// => results of latInterpol, lngInterpol always within range -180° ... +180° => conversion into values < -180° or > + 180° has to be done afterwards
var latInterpol = 180 / Math.PI * Math.atan2(z, Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
var lngInterpol = 180 / Math.PI * Math.atan2(y, x);
// don't split polyline if it crosses dateline ( -180° or +180°). Without the polyline would look like: +179° ==> +180° ==> -180° ==> -179°...
// algo: if difference lngInterpol-from.lng is > 180° there's been an unwanted split from +180 to -180 cause an arc can never span >180°
var diff = lngInterpol-fromLng*180/Math.PI;
function trunc(n) { return Math[n > 0 ? "floor" : "ceil"](n); } // alternatively we could use the new Math.trunc method, but Internet Explorer doesn't know it
if (diff < 0) {
lngInterpol = lngInterpol - trunc ((diff - 180)/ 360) * 360;
} else {
lngInterpol = lngInterpol - trunc ((diff +180)/ 360) * 360;
}
return [latInterpol, lngInterpol];
}
function _GCarc (npoints) {
var arrArcCoords = [];
var delta = 1.0 / (npoints-1 );
// first point of Arc should NOT be returned
for (var i = 0; i < npoints; i++) {
var step = delta * i;
var coordPair = _GCinterpolate (step);
arrArcCoords.push (coordPair);
}
return arrArcCoords;
}
var fromLat = _from.lat; // work with with copies of object's elements _from.lat and _from.lng, otherwise they would get modiefied due to call-by-reference on Objects in Javascript
var fromLng = _from.lng;
var toLat = _to.lat;
var toLng = _to.lng;
fromLat=fromLat * Math.PI / 180;
fromLng=fromLng * Math.PI / 180;
toLat=toLat * Math.PI / 180;
toLng=toLng * Math.PI / 180;
var d = 2.0 * Math.asin(Math.sqrt(Math.pow (Math.sin((fromLat - toLat) / 2.0), 2) + Math.cos(fromLat) * Math.cos(toLat) * Math.pow(Math.sin((fromLng - toLng) / 2.0), 2)));
var arrLatLngs;
if (d === 0) {
arrLatLngs = [[fromLat, fromLng]];
} else {
arrLatLngs = _GCarc(this._arcpoints);
}
return arrLatLngs;
},
_polyline: function (_from, _to) {
return [[_from.lat, _from.lng], [_to.lat, _to.lng]];
},
/**
* Update the tooltip distance
* @param {Number} total Total distance
* @param {Number} difference Difference in distance between 2 points
* @private
*/
_updateTooltip: function (currentTooltip, prevTooltip, total, difference, lastCircleCoords, mouseCoords) {
// Explanation of formula: http://www.movable-type.co.uk/scripts/latlong.html
var calcAngle = function (p1, p2, direction) {
var lat1 = p1.lat / 180 * Math.PI;
var lat2 = p2.lat / 180 * Math.PI;
var lng1 = p1.lng / 180 * Math.PI;
var lng2 = p2.lng / 180 * Math.PI;
var y = Math.sin(lng2-lng1) * Math.cos(lat2);
var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(lng2-lng1);
if (direction === "inbound") {
var brng = (Math.atan2(y, x) * 180 / Math.PI + 180).toFixed(0);
} else {
var brng = (Math.atan2(y, x) * 180 / Math.PI + 360).toFixed(0);
}
return (brng % 360);
}
var angleIn = calcAngle (mouseCoords, lastCircleCoords, "inbound");
var angleOut = calcAngle (lastCircleCoords, mouseCoords, "outbound");
var totalRound = this._getDistance (total);
var differenceRound = this._getDistance (difference);
var textCurrent = '';
if (differenceRound.value > 0 ) {
if (this.options.showBearings === true) {
textCurrent = this.options.bearingTextIn + ': ' + angleIn + '°<br>'+this.options.bearingTextOut+':---°';
}
textCurrent += '<div class="polyline-measure-tooltip-difference">+' + differenceRound.value + ' ' + differenceRound.unit + '</div>';
}
textCurrent += '<div class="polyline-measure-tooltip-total">' + totalRound.value + ' ' + totalRound.unit + '</div>';
currentTooltip._icon.innerHTML = textCurrent;
if ((this.options.showBearings === true) && (prevTooltip)) {
var textPrev = prevTooltip._icon.innerHTML;
var regExp = new RegExp(this.options.bearingTextOut + '.*\°');
var textReplace = textPrev.replace(regExp, this.options.bearingTextOut + ': ' + angleOut + "°");
prevTooltip._icon.innerHTML = textReplace;
}
},
_drawArrow: function (arcLine) {
var midpoint = Math.round(arcLine.length/2);
var P1 = arcLine[midpoint-1];
var P2 = arcLine[midpoint];
if (arcLine.length == 2) {
P1 = arcLine[0];
P2 = arcLine[1];
}
var diffLng12 = P2[1] - P1[1];
var diffLat12 = P2[0] - P1[0];
var center = [P1[0] + diffLat12/2, P1[1] + diffLng12/2]; // center of Great-circle distance, NOT of the arc on a Mercator map! reason: a) to complicated b) map not always Mercator c) good optical feature to see where real center of distance is not the "virtual" warped arc center due to Mercator projection
// angle just an aprroximation, which could be somewhat off if Line runs near high latitudes. Use of *geographical coords* for line segment P1 to P2 is best method. Use of *Pixel coords* for just one arc segement P1 to P2 could create for short lines unexact rotation angles, and the use Use of Pixel coords between endpoints [0] to [99] (in case of 100-point-arc) results in even more rotation difference for high latitudes as with geogrpaphical coords-method
var cssAngle = -Math.atan2(diffLat12, diffLng12)*57.29578 // convert radiant to degree as needed for use as CSS value; cssAngle is opposite to mathematical angle.
var iconArrow = L.divIcon ({
className: "", // to avoid getting a default class with paddings and borders assigned by Leaflet
iconSize: [16, 16],
iconAnchor: [8, 8],
// html : "<img src='iconArrow.png' style='background:green; height:100%; vertical-align:top; transform:rotate("+ cssAngle +"deg)'>" <<=== alternative method by the use of an image instead of a Unicode symbol.
html : "<div style = 'color:" + this.options.arrow.color + "; font-size: 16px; line-height: 16px; vertical-align:top; transform: rotate("+ cssAngle +"deg)'>➤</div>" // best results if iconSize = font-size = line-height and iconAnchor font-size/2 .both values needed to position symbol in center of L.divIcon for all font-sizes.
});
var newArrowMarker = L.marker (center, {icon: iconArrow, zIndexOffset:-50}).addTo(this._layerPaint); // zIndexOffset to draw arrows below tooltips
if (!this._currentLine){ // just bind tooltip if not drawing line anymore, cause following the instruction of tooltip is just possible when not drawing a line
newArrowMarker.bindTooltip (this.options.tooltipTextAdd, {direction:'top', opacity:0.7, className:'polyline-measure-popupTooltip'});
}
newArrowMarker.on ('click', this._clickedArrow, this);
return newArrowMarker;
},
/**
* Event to fire on mouse move
* @param {Object} e Event
* @private
*/
_mouseMove: function (e) {
var mouseCoords = e.latlng;
this._map.on ('click', this._mouseClick, this); // necassary for _dragCircle. If switched on already within _dragCircle an unwanted click is fired at the end of the drag.
if(!mouseCoords || !this._currentLine) {
return;
}
var lastCircleCoords = this._currentLine.circleCoords.last();
this._rubberlinePath.setLatLngs (this._polyline (lastCircleCoords, mouseCoords));
var currentTooltip = this._currentLine.tooltips.last();
var prevTooltip = this._currentLine.tooltips.slice(-2,-1)[0];
currentTooltip.setLatLng (mouseCoords);
var distanceSegment = mouseCoords.distanceTo (lastCircleCoords);
this._updateTooltip (currentTooltip, prevTooltip, this._currentLine.distance + distanceSegment, distanceSegment, lastCircleCoords, mouseCoords);
},
_startLine: function (clickCoords) {
var icon = L.divIcon({
className: 'polyline-measure-tooltip',
iconAnchor: [-4, -4]
});
var last = function() {
return this.slice(-1)[0];
};
this._rubberlinePath = L.polyline ([], {
// Style of temporary, dashed line while moving the mouse
color: this.options.tempLine.color,
weight: this.options.tempLine.weight,
interactive: false,
dashArray: '8,8'
}).addTo(this._layerPaint).bringToBack();
var polylineState = this; // use "polylineState" instead of "this" to allow measuring on 2 different maps the same time
this._currentLine = {
id: 0,
circleCoords: [],
circleMarkers: [],
arrowMarkers: [],
tooltips: [],
distance: 0,
polylinePath: L.polyline([], {
// Style of fixed, polyline after mouse is clicked
color: this.options.fixedLine.color,
weight: this.options.fixedLine.weight,
interactive: false
}).addTo(this._layerPaint).bringToBack(),
handleMarkers: function (latlng) {
// update style on previous marker
var lastCircleMarker = this.circleMarkers.last();
if (lastCircleMarker) {
lastCircleMarker.bindTooltip (polylineState.options.tooltipTextDelete, {direction:'top', opacity:0.7, className:'polyline-measure-popupTooltip'});
lastCircleMarker.off ('click', polylineState._finishPolylinePath, polylineState);
if (this.circleMarkers.length === 1) {
lastCircleMarker.setStyle (polylineState.options.startCircle);
} else {
lastCircleMarker.setStyle (polylineState.options.intermedCircle);
}
}
var newCircleMarker = new L.CircleMarker (latlng, polylineState.options.currentCircle).addTo(polylineState._layerPaint);
newCircleMarker.bindTooltip (polylineState.options.tooltipTextFinish + polylineState.options.tooltipTextDelete, {direction:'top', opacity:0.7, className:'polyline-measure-popupTooltip'});
newCircleMarker.cntLine = polylineState._currentLine.id;
newCircleMarker.cntCircle = polylineState._cntCircle;
polylineState._cntCircle++;
newCircleMarker.on ('mousedown', polylineState._dragCircle, polylineState);
newCircleMarker.on ('click', polylineState._finishPolylinePath, polylineState);
this.circleMarkers.push (newCircleMarker);
},
getNewToolTip: function(latlng) {
return L.marker (latlng, {
icon: icon,
interactive: false
});
},
addPoint: function (mouseCoords) {
var lastCircleCoords = this.circleCoords.last();
if (lastCircleCoords && lastCircleCoords.equals (mouseCoords)) { // don't add a new circle if the click was onto the last circle
return;
}
this.circleCoords.push (mouseCoords);
// update polyline
if (this.circleCoords.length > 1) {
var arc = polylineState._polyline (lastCircleCoords, mouseCoords);
var arrowMarker = polylineState._drawArrow (arc);
if (this.circleCoords.length > 2) {
arc.shift(); // remove first coordinate of the arc, cause it is identical with last coordinate of previous arc
}
this.polylinePath.setLatLngs (this.polylinePath.getLatLngs().concat(arc));
// following lines needed especially for Mobile Browsers where we just use mouseclicks. No mousemoves, no tempLine.
arrowMarker.cntLine = polylineState._currentLine.id;
arrowMarker.cntArrow = polylineState._cntCircle - 1;
polylineState._currentLine.arrowMarkers.push (arrowMarker);
var distanceSegment = lastCircleCoords.distanceTo (mouseCoords);
this.distance += distanceSegment;
var currentTooltip = polylineState._currentLine.tooltips.last();
var prevTooltip = polylineState._currentLine.tooltips.slice(-1,-2)[0];
polylineState._updateTooltip (currentTooltip, prevTooltip, this.distance, distanceSegment, lastCircleCoords, mouseCoords);
}
// update last tooltip with final value
if (currentTooltip) {
currentTooltip.setLatLng (mouseCoords);
}
// add new tooltip to update on mousemove
var tooltipNew = this.getNewToolTip(mouseCoords);
tooltipNew.addTo(polylineState._layerPaint);
this.tooltips.push (tooltipNew);
this.handleMarkers (mouseCoords);
},
finalize: function() {
// remove tooltip created by last click
polylineState._layerPaint.removeLayer (this.tooltips.last());
this.tooltips.pop();
// remove temporary rubberline
polylineState._layerPaint.removeLayer (polylineState._rubberlinePath);
if (this.circleCoords.length > 1) {
this.tooltips.last()._icon.classList.add('polyline-measure-tooltip-end'); // add Class e.g. another background-color to the Previous Tooltip (which is the last fixed tooltip, cause the moving tooltip is being deleted later)
var lastCircleMarker = this.circleMarkers.last()
lastCircleMarker.setStyle (polylineState.options.endCircle);
// use Leaflet's own tooltip method to shwo a popuo tooltip if user hovers the last circle of a polyline
lastCircleMarker.unbindTooltip (); // to close the opened Tooltip after it's been opened after click onto point to finish the line
polylineState._currentLine.circleMarkers.map (function (circle) {circle.bindTooltip (polylineState.options.tooltipTextMove + polylineState.options.tooltipTextDelete, {direction:'top', opacity:0.7, className:'polyline-measure-popupTooltip'})});
polylineState._currentLine.circleMarkers[0].bindTooltip (polylineState.options.tooltipTextMove + polylineState.options.tooltipTextDelete + polylineState.options.tooltipTextResume, {direction:'top', opacity:0.7, className:'polyline-measure-popupTooltip'});
lastCircleMarker.bindTooltip (polylineState.options.tooltipTextMove + polylineState.options.tooltipTextDelete + polylineState.options.tooltipTextResume, {direction:'top', opacity:0.7, className:'polyline-measure-popupTooltip'});
polylineState._currentLine.arrowMarkers.map (function (arrow) {arrow.bindTooltip (polylineState.options.tooltipTextAdd, {direction:'top', opacity:0.7, className:'polyline-measure-popupTooltip'})});
lastCircleMarker.off ('click', polylineState._finishPolylinePath, polylineState);
lastCircleMarker.on ('click', polylineState._resumePolylinePath, polylineState);
polylineState._arrPolylines.push(this);
} else {
// if there is only one point, just clean it up
polylineState._layerPaint.removeLayer (this.circleMarkers.last());
polylineState._layerPaint.removeLayer (this.tooltips.last());
}
polylineState._resetPathVariables();
}
};
var firstTooltip = L.marker (clickCoords, {
icon: icon,
interactive: false
})
firstTooltip.addTo(this._layerPaint);
var text = '';
if (this.options.showBearings === true) {
text = this.options.bearingTextIn+':---°<br>'+this.options.bearingTextOut+':---°';
}
text = text + '<div class="polyline-measure-tooltip-difference">+' + '0</div>';
text = text + '<div class="polyline-measure-tooltip-total">' + '0</div>';
firstTooltip._icon.innerHTML = text;
this._currentLine.tooltips.push (firstTooltip);
this._currentLine.circleCoords.last = last;
this._currentLine.tooltips.last = last;
this._currentLine.circleMarkers.last = last;
this._currentLine.id = this._arrPolylines.length;
},
/**
* Event to fire on mouse click
* @param {Object} e Event
* @private
*/
_mouseClick: function (e) {
// skip if there are no coords provided by the event, or this event's screen coordinates match those of finishing CircleMarker for the line we just completed
if (!e.latlng || (this._finishCircleScreencoords && this._finishCircleScreencoords.equals(e.containerPoint))) {
return;
}
if (!this._currentLine && !this._mapdragging) {
this._startLine (e.latlng);
this._map.fire('polylinemeasure:start', this._currentLine);
}
// just create a point if the map isn't dragged during the mouseclick.
if (!this._mapdragging) {
this._currentLine.addPoint (e.latlng);
this._map.fire('polylinemeasure:add', e);
this._map.fire('polylinemeasure:change', this._currentLine);
} else {
this._mapdragging = false; // this manual setting to "false" needed, instead of a "moveend"-Event. Cause the mouseclick of a "moveend"-event immediately would create a point too the same time.
}
},
/**
* Finish the drawing of the path by clicking onto the last circle or pressing ESC-Key
* @private
*/
_finishPolylinePath: function (e) {
this._map.fire('polylinemeasure:finish', this._currentLine);
this._currentLine.finalize();
if (e) {
this._finishCircleScreencoords = e.containerPoint;
}
},
/**
* Resume the drawing of a polyline by pressing CTRL-Key and clicking onto the last circle
* @private
*/
_resumePolylinePath: function (e) {
if (e.originalEvent.ctrlKey === true) { // just resume if user pressed the CTRL-Key while clicking onto the last circle
this._currentLine = this._arrPolylines [e.target.cntLine];
this._rubberlinePath = L.polyline ([], {
// Style of temporary, rubberline while moving the mouse
color: this.options.tempLine.color,
weight: this.options.tempLine.weight,
interactive: false,
dashArray: '8,8'
}).addTo(this._layerPaint).bringToBack();
this._currentLine.tooltips.last()._icon.classList.remove ('polyline-measure-tooltip-end'); // remove extra CSS-class of previous, last tooltip
var tooltipNew = this._currentLine.getNewToolTip (e.latlng);
tooltipNew.addTo (this._layerPaint);
this._currentLine.tooltips.push(tooltipNew);
this._currentLine.circleMarkers.last().unbindTooltip(); // remove popup-tooltip of previous, last circleMarker
this._currentLine.circleMarkers.last().bindTooltip (this.options.tooltipTextMove + this.options.tooltipTextDelete, {direction:'top', opacity:0.7, className:'polyline-measure-popupTooltip'});
this._currentLine.circleMarkers.last().setStyle (this.options.currentCircle);