forked from rstudio/leaflet
-
Notifications
You must be signed in to change notification settings - Fork 3
/
methods.js
1311 lines (1145 loc) · 43.4 KB
/
methods.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
import $ from "./global/jquery";
import L from "./global/leaflet";
import Shiny from "./global/shiny";
import HTMLWidgets from "./global/htmlwidgets";
import { asArray } from "./util";
import { getCRS } from "./crs_utils";
import DataFrame from "./dataframe";
import ClusterLayerStore from "./cluster-layer-store";
import Mipmapper from "./mipmapper";
let methods = {};
export default methods;
function mouseHandler(mapId, layerId, group, eventName, extraInfo) {
return function(e) {
if (!HTMLWidgets.shinyMode) return;
let eventInfo = $.extend(
{
id: layerId,
".nonce": Math.random() // force reactivity
},
group !== null ? {group: group} : null,
e.target.getLatLng ? e.target.getLatLng() : e.latlng,
extraInfo
);
Shiny.onInputChange(mapId + "_" + eventName, eventInfo);
};
}
methods.mouseHandler = mouseHandler;
methods.clearGroup = function(group) {
$.each(asArray(group), (i, v) => {
this.layerManager.clearGroup(v);
});
};
methods.setView = function(center, zoom, options) {
this.setView(center, zoom, options);
};
methods.fitBounds = function(lat1, lng1, lat2, lng2) {
this.fitBounds([
[lat1, lng1], [lat2, lng2]
]);
};
methods.setMaxBounds = function(lat1, lng1, lat2, lng2) {
this.setMaxBounds([
[lat1, lng1], [lat2, lng2]
]);
};
methods.addPopups = function(lat, lng, popup, layerId, group, options) {
let df = new DataFrame()
.col("lat", lat)
.col("lng", lng)
.col("popup", popup)
.col("layerId", layerId)
.col("group", group)
.cbind(options);
for (let i = 0; i < df.nrow(); i++) {
if($.isNumeric(df.get(i, "lat")) && $.isNumeric(df.get(i, "lng"))) {
(function() {
let popup = L.popup(df.get(i))
.setLatLng([df.get(i, "lat"), df.get(i, "lng")])
.setContent(df.get(i, "popup"));
let thisId = df.get(i, "layerId");
let thisGroup = df.get(i, "group");
this.layerManager.addLayer(popup, "popup", thisId, thisGroup);
}).call(this);
}
}
};
methods.removePopup = function(layerId) {
this.layerManager.removeLayer("popup", layerId);
};
methods.clearPopups = function() {
this.layerManager.clearLayers("popup");
};
methods.addTiles = function(urlTemplate, layerId, group, options) {
this.layerManager.addLayer(L.tileLayer(urlTemplate, options), "tile", layerId, group);
};
methods.removeTiles = function(layerId) {
this.layerManager.removeLayer("tile", layerId);
};
methods.clearTiles = function() {
this.layerManager.clearLayers("tile");
};
methods.addWMSTiles = function(baseUrl, layerId, group, options) {
if(options && options.crs) {
options.crs = getCRS(options.crs);
}
this.layerManager.addLayer(L.tileLayer.wms(baseUrl, options), "tile", layerId, group);
};
// Given:
// {data: ["a", "b", "c"], index: [0, 1, 0, 2]}
// returns:
// ["a", "b", "a", "c"]
function unpackStrings(iconset) {
if (!iconset) {
return iconset;
}
if (typeof(iconset.index) === "undefined") {
return iconset;
}
iconset.data = asArray(iconset.data);
iconset.index = asArray(iconset.index);
return $.map(iconset.index, function(e, i) {
return iconset.data[e];
});
}
function addMarkers(map, df, group, clusterOptions, clusterId, markerFunc) {
(function() {
let clusterGroup = this.layerManager.getLayer("cluster", clusterId),
cluster = clusterOptions !== null;
if (cluster && !clusterGroup) {
clusterGroup = L.markerClusterGroup.layerSupport(clusterOptions);
if(clusterOptions.freezeAtZoom) {
let freezeAtZoom = clusterOptions.freezeAtZoom;
delete clusterOptions.freezeAtZoom;
clusterGroup.freezeAtZoom(freezeAtZoom);
}
clusterGroup.clusterLayerStore = new ClusterLayerStore(clusterGroup);
}
let extraInfo = cluster ? { clusterId: clusterId } : {};
for (let i = 0; i < df.nrow(); i++) {
if($.isNumeric(df.get(i, "lat")) && $.isNumeric(df.get(i, "lng"))) {
(function() {
let marker = markerFunc(df, i);
let thisId = df.get(i, "layerId");
let thisGroup = cluster ? null : df.get(i, "group");
if (cluster) {
clusterGroup.clusterLayerStore.add(marker, thisId);
} else {
this.layerManager.addLayer(marker, "marker", thisId, thisGroup, df.get(i, "ctGroup", true), df.get(i, "ctKey", true));
}
let popup = df.get(i, "popup");
let popupOptions = df.get(i, "popupOptions");
if (popup !== null) {
if (popupOptions !== null){
marker.bindPopup(popup, popupOptions);
} else {
marker.bindPopup(popup);
}
}
let label = df.get(i, "label");
let labelOptions = df.get(i, "labelOptions");
if (label !== null) {
if (labelOptions !== null) {
if(labelOptions.noHide) {
marker.bindLabel(label, labelOptions).showLabel();
} else {
marker.bindLabel(label, labelOptions);
}
} else {
marker.bindLabel(label);
}
}
marker.on("click", mouseHandler(this.id, thisId, thisGroup, "marker_click", extraInfo), this);
marker.on("mouseover", mouseHandler(this.id, thisId, thisGroup, "marker_mouseover", extraInfo), this);
marker.on("mouseout", mouseHandler(this.id, thisId, thisGroup, "marker_mouseout", extraInfo), this);
}).call(this);
}
}
if (cluster) {
this.layerManager.addLayer(clusterGroup, "cluster", clusterId, group);
}
}).call(map);
}
methods.addGenericMarkers = addMarkers;
methods.addMarkers = function(lat, lng, icon, layerId, group, options, popup, popupOptions,
clusterOptions, clusterId, label, labelOptions, crosstalkOptions) {
let icondf;
let getIcon;
if (icon) {
// Unpack icons
icon.iconUrl = unpackStrings(icon.iconUrl);
icon.iconRetinaUrl = unpackStrings(icon.iconRetinaUrl);
icon.shadowUrl = unpackStrings(icon.shadowUrl);
icon.shadowRetinaUrl = unpackStrings(icon.shadowRetinaUrl);
// This cbinds the icon URLs and any other icon options; they're all
// present on the icon object.
icondf = new DataFrame().cbind(icon);
// Constructs an icon from a specified row of the icon dataframe.
getIcon = function(i) {
let opts = icondf.get(i);
if (!opts.iconUrl) {
return new L.Icon.Default();
}
// Composite options (like points or sizes) are passed from R with each
// individual component as its own option. We need to combine them now
// into their composite form.
if (opts.iconWidth) {
opts.iconSize = [opts.iconWidth, opts.iconHeight];
}
if (opts.shadowWidth) {
opts.shadowSize = [opts.shadowWidth, opts.shadowHeight];
}
if (opts.iconAnchorX) {
opts.iconAnchor = [opts.iconAnchorX, opts.iconAnchorY];
}
if (opts.shadowAnchorX) {
opts.shadowAnchor = [opts.shadowAnchorX, opts.shadowAnchorY];
}
if (opts.popupAnchorX) {
opts.popupAnchor = [opts.popupAnchorX, opts.popupAnchorY];
}
return new L.Icon(opts);
};
}
if(!($.isEmptyObject(lat) || $.isEmptyObject(lng)) ||
($.isNumeric(lat) && $.isNumeric(lng))) {
let df = new DataFrame()
.col("lat", lat)
.col("lng", lng)
.col("layerId", layerId)
.col("group", group)
.col("popup", popup)
.col("popupOptions", popupOptions)
.col("label", label)
.col("labelOptions", labelOptions)
.cbind(options)
.cbind(crosstalkOptions || {});
if (icon) icondf.effectiveLength = df.nrow();
addMarkers(this, df, group, clusterOptions, clusterId, (df, i) => {
let options = df.get(i);
if (icon) options.icon = getIcon(i);
return L.marker([df.get(i, "lat"), df.get(i, "lng")], options);
});
}
};
methods.addAwesomeMarkers = function(lat, lng, icon, layerId, group, options, popup, popupOptions,
clusterOptions, clusterId, label, labelOptions, crosstalkOptions) {
let icondf;
let getIcon;
if (icon) {
// This cbinds the icon URLs and any other icon options; they're all
// present on the icon object.
icondf = new DataFrame().cbind(icon);
// Constructs an icon from a specified row of the icon dataframe.
getIcon = function(i) {
let opts = icondf.get(i);
if (!opts) {
return new L.AwesomeMarkers.icon();
}
if(opts.squareMarker) {
opts.className = "awesome-marker awesome-marker-square";
}
return new L.AwesomeMarkers.icon(opts);
};
}
if(!($.isEmptyObject(lat) || $.isEmptyObject(lng)) ||
($.isNumeric(lat) && $.isNumeric(lng))) {
let df = new DataFrame()
.col("lat", lat)
.col("lng", lng)
.col("layerId", layerId)
.col("group", group)
.col("popup", popup)
.col("popupOptions", popupOptions)
.col("label", label)
.col("labelOptions", labelOptions)
.cbind(options)
.cbind(crosstalkOptions || {});
if (icon) icondf.effectiveLength = df.nrow();
addMarkers(this, df, group, clusterOptions, clusterId, function(df, i) {
let options = df.get(i);
if (icon) options.icon = getIcon(i);
return L.marker([df.get(i, "lat"), df.get(i, "lng")], options);
});
}
};
function addLayers(map, category, df, layerFunc) {
for (let i = 0; i < df.nrow(); i++) {
(function() {
let layer = layerFunc(df, i);
if(!$.isEmptyObject(layer)) {
let thisId = df.get(i, "layerId");
let thisGroup = df.get(i, "group");
this.layerManager.addLayer(layer, category, thisId, thisGroup, df.get(i, "ctGroup", true), df.get(i, "ctKey", true));
if (layer.bindPopup) {
let popup = df.get(i, "popup");
let popupOptions = df.get(i, "popupOptions");
if (popup !== null) {
if (popupOptions !== null){
layer.bindPopup(popup, popupOptions);
} else {
layer.bindPopup(popup);
}
}
}
if (layer.bindLabel) {
let label = df.get(i, "label");
let labelOptions = df.get(i, "labelOptions");
if (label !== null) {
if (labelOptions !== null) {
layer.bindLabel(label, labelOptions);
} else {
layer.bindLabel(label);
}
}
}
layer.on("click", mouseHandler(this.id, thisId, thisGroup, category + "_click"), this);
layer.on("mouseover", mouseHandler(this.id, thisId, thisGroup, category + "_mouseover"), this);
layer.on("mouseout", mouseHandler(this.id, thisId, thisGroup, category + "_mouseout"), this);
let highlightStyle = df.get(i,"highlightOptions");
if(!$.isEmptyObject(highlightStyle)) {
let defaultStyle = {};
$.each(highlightStyle, function (k, v) {
if(k != "bringToFront" && k != "sendToBack"){
if(df.get(i,k)) {
defaultStyle[k] = df.get(i,k);
}
}
});
layer.on("mouseover",
function(e) {
this.setStyle(highlightStyle);
if(highlightStyle.bringToFront) {
this.bringToFront();
}
});
layer.on("mouseout",
function(e) {
this.setStyle(defaultStyle);
if(highlightStyle.sendToBack) {
this.bringToBack();
}
});
}
}
}).call(map);
}
}
methods.addGenericLayers = addLayers;
methods.addCircles = function(lat, lng, radius, layerId, group, options, popup, popupOptions, label, labelOptions, highlightOptions, crosstalkOptions) {
if(!($.isEmptyObject(lat) || $.isEmptyObject(lng)) ||
($.isNumeric(lat) && $.isNumeric(lng))) {
let df = new DataFrame()
.col("lat", lat)
.col("lng", lng)
.col("radius", radius)
.col("layerId", layerId)
.col("group", group)
.col("popup", popup)
.col("popupOptions", popupOptions)
.col("label", label)
.col("labelOptions", labelOptions)
.col("highlightOptions", highlightOptions)
.cbind(options)
.cbind(crosstalkOptions || {});
addLayers(this, "shape", df, function(df, i) {
if($.isNumeric(df.get(i, "lat")) && $.isNumeric(df.get(i, "lng")) &&
$.isNumeric(df.get(i,"radius"))) {
return L.circle([df.get(i, "lat"), df.get(i, "lng")], df.get(i, "radius"), df.get(i));
} else {
return null;
}
});
}
};
methods.addCircleMarkers = function(lat, lng, radius, layerId, group, options, clusterOptions, clusterId, popup, popupOptions, label, labelOptions, crosstalkOptions) {
if(!($.isEmptyObject(lat) || $.isEmptyObject(lng)) ||
($.isNumeric(lat) && $.isNumeric(lng))) {
let df = new DataFrame()
.col("lat", lat)
.col("lng", lng)
.col("radius", radius)
.col("layerId", layerId)
.col("group", group)
.col("popup", popup)
.col("popupOptions", popupOptions)
.col("label", label)
.col("labelOptions", labelOptions)
.cbind(crosstalkOptions || {})
.cbind(options);
addMarkers(this, df, group, clusterOptions, clusterId, function(df, i) {
return L.circleMarker([df.get(i, "lat"), df.get(i, "lng")], df.get(i));
});
}
};
/*
* @param lat Array of arrays of latitude coordinates for polylines
* @param lng Array of arrays of longitude coordinates for polylines
*/
methods.addPolylines = function(polygons, layerId, group, options, popup, popupOptions, label, labelOptions, highlightOptions, crosstalkOptions) {
if(polygons.length>0) {
let df = new DataFrame()
.col("shapes", polygons)
.col("layerId", layerId)
.col("group", group)
.col("popup", popup)
.col("popupOptions", popupOptions)
.col("label", label)
.col("labelOptions", labelOptions)
.col("highlightOptions", highlightOptions)
.cbind(options)
.cbind(crosstalkOptions || {});
addLayers(this, "shape", df, function(df, i) {
let shapes = df.get(i, "shapes");
shapes = shapes.map(shape => HTMLWidgets.dataframeToD3(shape[0]));
if(shapes.length>1) {
return L.multiPolyline(shapes, df.get(i));
} else {
return L.polyline(shapes[0], df.get(i));
}
});
}
};
methods.removeMarker = function(layerId) {
this.layerManager.removeLayer("marker", layerId);
};
methods.clearMarkers = function() {
this.layerManager.clearLayers("marker");
};
methods.removeMarkerCluster = function(layerId) {
this.layerManager.removeLayer("cluster", layerId);
};
methods.removeMarkerFromCluster = function(layerId, clusterId) {
let cluster = this.layerManager.getLayer("cluster", clusterId);
if (!cluster) return;
cluster.clusterLayerStore.remove(layerId);
};
methods.clearMarkerClusters = function() {
this.layerManager.clearLayers("cluster");
};
methods.removeShape = function(layerId) {
this.layerManager.removeLayer("shape", layerId);
};
methods.clearShapes = function() {
this.layerManager.clearLayers("shape");
};
methods.addRectangles = function(lat1, lng1, lat2, lng2, layerId, group, options, popup, popupOptions, label, labelOptions, highlightOptions, crosstalkOptions) {
let df = new DataFrame()
.col("lat1", lat1)
.col("lng1", lng1)
.col("lat2", lat2)
.col("lng2", lng2)
.col("layerId", layerId)
.col("group", group)
.col("popup", popup)
.col("popupOptions", popupOptions)
.col("label", label)
.col("labelOptions", labelOptions)
.col("highlightOptions", highlightOptions)
.cbind(options)
.cbind(crosstalkOptions || {});
addLayers(this, "shape", df, function(df, i) {
if($.isNumeric(df.get(i, "lat1")) && $.isNumeric(df.get(i, "lng1")) &&
$.isNumeric(df.get(i, "lat2")) && $.isNumeric(df.get(i, "lng2"))) {
return L.rectangle(
[
[df.get(i, "lat1"), df.get(i, "lng1")],
[df.get(i, "lat2"), df.get(i, "lng2")]
],
df.get(i));
} else {
return null;
}
});
};
/*
* @param lat Array of arrays of latitude coordinates for polygons
* @param lng Array of arrays of longitude coordinates for polygons
*/
methods.addPolygons = function(polygons, layerId, group, options, popup, popupOptions, label, labelOptions, highlightOptions, crosstalkOptions) {
if(polygons.length>0) {
let df = new DataFrame()
.col("shapes", polygons)
.col("layerId", layerId)
.col("group", group)
.col("popup", popup)
.col("popupOptions", popupOptions)
.col("label", label)
.col("labelOptions", labelOptions)
.col("highlightOptions", highlightOptions)
.cbind(options)
.cbind(crosstalkOptions || {});
addLayers(this, "shape", df, function(df, i) {
// This code used to use L.multiPolygon, but that caused
// double-click on a multipolygon to fail to zoom in on the
// map. Surprisingly, putting all the rings in a single
// polygon seems to still work; complicated multipolygons
// are still rendered correctly.
let shapes = df.get(i, "shapes")
.map(polygon => polygon.map(HTMLWidgets.dataframeToD3))
.reduce((acc, val) => acc.concat(val), []);
return L.polygon(shapes, df.get(i));
});
}
};
methods.addGeoJSON = function(data, layerId, group, style) {
// This time, self is actually needed because the callbacks below need
// to access both the inner and outer senses of "this"
let self = this;
if (typeof(data) === "string") {
data = JSON.parse(data);
}
let globalStyle = $.extend({}, style, data.style || {});
let gjlayer = L.geoJson(data, {
style: function(feature) {
if (feature.style || feature.properties.style) {
return $.extend({}, globalStyle, feature.style, feature.properties.style);
} else {
return globalStyle;
}
},
onEachFeature: function(feature, layer) {
let extraInfo = {
featureId: feature.id,
properties: feature.properties
};
let popup = feature.properties.popup;
if (typeof popup !== "undefined" && popup !== null) layer.bindPopup(popup);
layer.on("click", mouseHandler(self.id, layerId, group, "geojson_click", extraInfo), this);
layer.on("mouseover", mouseHandler(self.id, layerId, group, "geojson_mouseover", extraInfo), this);
layer.on("mouseout", mouseHandler(self.id, layerId, group, "geojson_mouseout", extraInfo), this);
}
});
this.layerManager.addLayer(gjlayer, "geojson", layerId, group);
};
methods.removeGeoJSON = function(layerId) {
this.layerManager.removeLayer("geojson", layerId);
};
methods.clearGeoJSON = function() {
this.layerManager.clearLayers("geojson");
};
methods.addTopoJSON = function(data, layerId, group, style) {
// This time, self is actually needed because the callbacks below need
// to access both the inner and outer senses of "this"
let self = this;
if (typeof(data) === "string") {
data = JSON.parse(data);
}
let globalStyle = $.extend({}, style, data.style || {});
let gjlayer = L.geoJson(null, {
style: function(feature) {
if (feature.style || feature.properties.style) {
return $.extend({}, globalStyle, feature.style, feature.properties.style);
} else {
return globalStyle;
}
},
onEachFeature: function(feature, layer) {
let extraInfo = {
featureId: feature.id,
properties: feature.properties
};
let popup = feature.properties.popup;
if (typeof popup !== "undefined" && popup !== null) layer.bindPopup(popup);
layer.on("click", mouseHandler(self.id, layerId, group, "topojson_click", extraInfo), this);
layer.on("mouseover", mouseHandler(self.id, layerId, group, "topojson_mouseover", extraInfo), this);
layer.on("mouseout", mouseHandler(self.id, layerId, group, "topojson_mouseout", extraInfo), this);
}
});
global.omnivore.topojson.parse(data, null, gjlayer);
this.layerManager.addLayer(gjlayer, "topojson", layerId, group);
};
methods.removeTopoJSON = function(layerId) {
this.layerManager.removeLayer("topojson", layerId);
};
methods.clearTopoJSON = function() {
this.layerManager.clearLayers("topojson");
};
methods.addControl = function(html, position, layerId, classes) {
function onAdd(map) {
let div = L.DomUtil.create("div", classes);
if (typeof layerId !== "undefined" && layerId !== null) {
div.setAttribute("id", layerId);
}
this._div = div;
// It's possible for window.Shiny to be true but Shiny.initializeInputs to
// not be, when a static leaflet widget is included as part of the shiny
// UI directly (not through leafletOutput or uiOutput). In this case we
// don't do the normal Shiny stuff as that will all happen when Shiny
// itself loads and binds the entire doc.
if (window.Shiny && Shiny.initializeInputs) {
Shiny.renderHtml(html, this._div);
Shiny.initializeInputs(this._div);
Shiny.bindAll(this._div);
} else {
this._div.innerHTML = html;
}
return this._div;
}
function onRemove(map) {
if (window.Shiny && Shiny.unbindAll) {
Shiny.unbindAll(this._div);
}
}
let Control = L.Control.extend({
options: {position: position},
onAdd: onAdd,
onRemove: onRemove
});
this.controls.add(new Control, layerId, html);
};
methods.addCustomControl = function(control, layerId) {
this.controls.add(control, layerId);
};
methods.removeControl = function(layerId) {
this.controls.remove(layerId);
};
methods.getControl = function(layerId) {
this.controls.get(layerId);
};
methods.clearControls = function() {
this.controls.clear();
};
methods.addLegend = function(options) {
let legend = L.control({position: options.position});
let gradSpan;
legend.onAdd = function (map) {
let div = L.DomUtil.create("div", options.className),
colors = options.colors,
labels = options.labels,
legendHTML = "";
if (options.type === "numeric") {
// # Formatting constants.
let singleBinHeight = 20; // The distance between tick marks, in px
let vMargin = 8; // If 1st tick mark starts at top of gradient, how
// many extra px are needed for the top half of the
// 1st label? (ditto for last tick mark/label)
let tickWidth = 4; // How wide should tick marks be, in px?
let labelPadding = 6; // How much distance to reserve for tick mark?
// (Must be >= tickWidth)
// # Derived formatting parameters.
// What's the height of a single bin, in percentage (of gradient height)?
// It might not just be 1/(n-1), if the gradient extends past the tick
// marks (which can be the case for pretty cut points).
let singleBinPct = (options.extra.p_n - options.extra.p_1) / (labels.length - 1);
// Each bin is `singleBinHeight` high. How tall is the gradient?
let totalHeight = (1 / singleBinPct) * singleBinHeight + 1;
// How far should the first tick be shifted down, relative to the top
// of the gradient?
let tickOffset = (singleBinHeight / singleBinPct) * options.extra.p_1;
gradSpan = $("<span/>").css({
"background": "linear-gradient(" + colors + ")",
"opacity": options.opacity,
"height": totalHeight + "px",
"width": "18px",
"display": "block",
"margin-top": vMargin + "px"
});
let leftDiv = $("<div/>").css("float", "left"),
rightDiv = $("<div/>").css("float", "left");
leftDiv.append(gradSpan);
$(div).append(leftDiv).append(rightDiv)
.append($("<br clear=\"both\"/>"));
// Have to attach the div to the body at this early point, so that the
// svg text getComputedTextLength() actually works, below.
document.body.appendChild(div);
let ns = "http://www.w3.org/2000/svg";
let svg = document.createElementNS(ns, "svg");
rightDiv.append(svg);
let g = document.createElementNS(ns, "g");
$(g).attr("transform", "translate(0, " + vMargin + ")");
svg.appendChild(g);
// max label width needed to set width of svg, and right-justify text
let maxLblWidth = 0;
// Create tick marks and labels
$.each(labels, function(i, label) {
let y = tickOffset + i*singleBinHeight + 0.5;
let thisLabel = document.createElementNS(ns, "text");
$(thisLabel)
.text(labels[i])
.attr("y", y)
.attr("dx", labelPadding)
.attr("dy", "0.5ex");
g.appendChild(thisLabel);
maxLblWidth = Math.max(maxLblWidth, thisLabel.getComputedTextLength());
let thisTick = document.createElementNS(ns, "line");
$(thisTick)
.attr("x1", 0)
.attr("x2", tickWidth)
.attr("y1", y)
.attr("y2", y)
.attr("stroke-width", 1);
g.appendChild(thisTick);
});
// Now that we know the max label width, we can right-justify
$(svg).find("text")
.attr("dx", labelPadding + maxLblWidth)
.attr("text-anchor", "end");
// Final size for <svg>
$(svg).css({
width: (maxLblWidth + labelPadding) + "px",
height: totalHeight + vMargin*2 + "px"
});
if (options.na_color) {
$(div).append("<div><i style=\"background:" + options.na_color +
";opacity:" + options.opacity +
";\"></i> " + options.na_label + "</div>");
}
} else {
if (options.na_color) {
colors.push(options.na_color);
labels.push(options.na_label);
}
for (let i = 0; i < colors.length; i++) {
legendHTML += "<i style=\"background:" + colors[i] + ";opacity:" +
options.opacity + "\"></i> " + labels[i] + "<br clear='both'/>";
}
div.innerHTML = legendHTML;
}
if (options.title)
$(div).prepend("<div style=\"margin-bottom:3px\"><strong>" +
options.title + "</strong></div>");
return div;
};
if(options.group) {
// Auto generate a layerID if not provided
if(!options.layerId) {
options.layerId = L.stamp(legend);
}
let map = this;
map.on("overlayadd", function(e){
if(e.name === options.group) {
map.controls.add(legend, options.layerId);
}
});
map.on("overlayremove", function(e){
if(e.name === options.group) {
map.controls.remove(options.layerId);
}
});
map.on("groupadd", function(e){
if(e.name === options.group) {
map.controls.add(legend, options.layerId);
}
});
map.on("groupremove", function(e){
if(e.name === options.group) {
map.controls.remove(options.layerId);
}
});
}
this.controls.add(legend, options.layerId);
};
methods.addLayersControl = function(baseGroups, overlayGroups, options) {
// Only allow one layers control at a time
methods.removeLayersControl.call(this);
let firstLayer = true;
let base = {};
$.each(asArray(baseGroups), (i, g) => {
let layer = this.layerManager.getLayerGroup(g, true);
if (layer) {
base[g] = layer;
// Check if >1 base layers are visible; if so, hide all but the first one
if (this.hasLayer(layer)) {
if (firstLayer) {
firstLayer = false;
} else {
this.removeLayer(layer);
}
}
}
});
let overlay = {};
$.each(asArray(overlayGroups), (i, g) => {
let layer = this.layerManager.getLayerGroup(g, true);
if (layer) {
overlay[g] = layer;
}
});
let layersControl = L.control.layers(base, overlay, options).addTo(this);
this.currentLayersControl = layersControl;
};
methods.removeLayersControl = function() {
if (this.currentLayersControl) {
this.currentLayersControl.removeFrom(this);
this.currentLayersControl = null;
}
};
methods.addScaleBar = function(options) {
// Only allow one scale bar at a time
methods.removeScaleBar.call(this);
let scaleBar = L.control.scale(options).addTo(this);
this.currentScaleBar = scaleBar;
};
methods.removeScaleBar = function() {
if (this.currentScaleBar) {
this.currentScaleBar.removeFrom(this);
this.currentScaleBar = null;
}
};
methods.hideGroup = function(group) {
$.each(asArray(group), (i, g) => {
let layer = this.layerManager.getLayerGroup(g, true);
if (layer) {
this.removeLayer(layer);
}
});
};
methods.showGroup = function(group) {
$.each(asArray(group), (i, g) => {
let layer = this.layerManager.getLayerGroup(g, true);
if (layer) {
this.addLayer(layer);
}
});
};
function setupShowHideGroupsOnZoom(map) {
if (map.leafletr._hasInitializedShowHideGroups) {
return;
}
map.leafletr._hasInitializedShowHideGroups = true;
function setVisibility(layer, visible, group) {
if (visible !== map.hasLayer(layer)) {
if (visible) {
map.addLayer(layer);
map.fire("groupadd", {"name": group, "layer": layer});
} else {
map.removeLayer(layer);
map.fire("groupremove", {"name": group, "layer": layer});
}
}
}
function showHideGroupsOnZoom() {
if (!map.layerManager)
return;
let zoom = map.getZoom();
map.layerManager.getAllGroupNames().forEach(group => {
let layer = map.layerManager.getLayerGroup(group, false);
if (layer && typeof(layer.zoomLevels) !== "undefined") {
setVisibility(layer,
layer.zoomLevels === true || layer.zoomLevels.indexOf(zoom) >= 0,
group);
}
});
}
map.showHideGroupsOnZoom = showHideGroupsOnZoom;
map.on("zoomend", showHideGroupsOnZoom);
}
methods.setGroupOptions = function(group, options) {
$.each(asArray(group), (i, g) => {
let layer = this.layerManager.getLayerGroup(g, true);
// This slightly tortured check is because 0 is a valid value for zoomLevels
if (typeof(options.zoomLevels) !== "undefined" && options.zoomLevels !== null) {
layer.zoomLevels = asArray(options.zoomLevels);
}
});
setupShowHideGroupsOnZoom(this);
this.showHideGroupsOnZoom();
};
methods.addRasterImage = function(uri, bounds, opacity, attribution, layerId, group) {
// uri is a data URI containing an image. We want to paint this image as a
// layer at (top-left) bounds[0] to (bottom-right) bounds[1].
// We can't simply use ImageOverlay, as it uses bilinear scaling which looks
// awful as you zoom in (and sometimes shifts positions or disappears).
// Instead, we'll use a TileLayer.Canvas to draw pieces of the image.
// First, some helper functions.
// degree2tile converts latitude, longitude, and zoom to x and y tile
// numbers. The tile numbers returned can be non-integral, as there's no
// reason to expect that the lat/lng inputs are exactly on the border of two
// tiles.
//
// We'll use this to convert the bounds we got from the server, into coords
// in tile-space at a given zoom level. Note that once we do the conversion,
// we don't to do any more trigonometry to convert between pixel coordinates
// and tile coordinates; the source image pixel coords, destination canvas
// pixel coords, and tile coords all can be scaled linearly.
function degree2tile(lat, lng, zoom) {
// See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
let latRad = lat * Math.PI / 180;
let n = Math.pow(2, zoom);
let x = (lng + 180) / 360 * n;
let y = (1 - Math.log(Math.tan(latRad) + (1 / Math.cos(latRad))) / Math.PI) / 2 * n;
return {x: x, y: y};
}
// Given a range [from,to) and either one or two numbers, returns true if
// there is any overlap between [x,x1) and the range--or if x1 is omitted,
// then returns true if x is within [from,to).
function overlap(from, to, x, /* optional */ x1) {
if (arguments.length == 3)
x1 = x;
return x < to && x1 >= from;
}
function getCanvasSmoothingProperty(ctx) {
let candidates = ["imageSmoothingEnabled", "mozImageSmoothingEnabled",