forked from grafana/worldmap-panel
-
Notifications
You must be signed in to change notification settings - Fork 31
/
worldmap.ts
609 lines (526 loc) · 18.3 KB
/
worldmap.ts
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
import * as _ from 'lodash';
import $ from 'jquery';
import './libs/leaflet_plus';
import * as L from 'leaflet';
import WorldmapCtrl from './worldmap_ctrl';
import { ColorModes } from './model';
import { LatLngExpression } from 'leaflet';
const tileServers = {
'CARTO Positron': {
url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
attribution:
'© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> ' +
'© <a href="https://carto.com/about-carto/" target="_blank" rel="noopener">CARTO</a>',
subdomains: 'abcd',
},
'CARTO Dark': {
url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
attribution:
'© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a> ' +
'© <a href="https://carto.com/about-carto/" target="_blank" rel="noopener">CARTO</a>',
subdomains: 'abcd',
},
};
export default class WorldMap {
ctrl: WorldmapCtrl;
mapContainer: any;
circles: any[];
map: any;
legend: any;
overlay: any;
circlesLayer: any;
constructor(ctrl, mapContainer) {
this.ctrl = ctrl;
this.mapContainer = mapContainer;
this.circles = [];
}
createMap() {
const center = this.ctrl.settings.center;
const mapCenter = (window as any).L.latLng(center.mapCenterLatitude, center.mapCenterLongitude);
const zoomLevel = this.getEffectiveZoomLevel(center.mapZoomLevel);
this.map = L.map(this.mapContainer, {
worldCopyJump: true,
preferCanvas: true,
center: mapCenter,
zoom: zoomLevel,
zoomControl: this.ctrl.settings.showZoomControl,
attributionControl: this.ctrl.settings.showAttribution,
});
this.setMouseWheelZoom();
this.setDragging();
this.setDoubleClickZoom();
const selectedTileServer = tileServers[this.ctrl.tileServer];
(window as any).L.tileLayer(selectedTileServer.url, {
maxZoom: 18,
subdomains: selectedTileServer.subdomains,
reuseTiles: true,
detectRetina: true,
attribution: selectedTileServer.attribution,
}).addTo(this.map);
}
renderMapFirst() {
const _this = this;
this.map.whenReady((ctx, options) => {
_this.renderMap({ animate: false });
});
}
renderMap(options?: {}) {
options = options || {};
_.defaults(options, { animate: true });
if (!this.legend && this.ctrl.settings.showLegend) {
this.createLegend();
}
console.info('Drawing circles');
this.drawCircles();
this.drawCustomAttribution();
setTimeout(() => {
this.drawMap(options);
}, 1);
}
drawMap(options?: {}) {
console.info('Drawing map');
this.resize();
if (this.ctrl.mapCenterMoved) {
this.panToMapCenter(options);
}
//this.ctrl.updatePanelCorner();
}
getEffectiveZoomLevel(zoomLevel) {
if (this.ctrl.settings.maximumZoom) {
zoomLevel = Math.min(parseInt(this.ctrl.settings.maximumZoom, 10), zoomLevel);
}
return zoomLevel;
}
private getLegendUpdateFunction() {
switch (this.ctrl.settings.colorMode) {
case ColorModes.categories.id:
return () => {
const legendHtml = this.ctrl.data.categories.reduce((html, cat, idx) => {
return (
html +
'<div class="legend-item"><i style="background:' +
this.ctrl.settings.colors[idx + 1] +
'"></i> ' +
cat +
'</div>'
);
}, '<div class="legend-item"><i style="background:' + this.ctrl.settings.colors[0] + '"></i> *</div>');
this.legend._div.innerHTML = legendHtml;
};
case ColorModes.threshold.id:
default:
return () => {
const thresholds = this.ctrl.data.thresholds;
let legendHtml = '';
legendHtml +=
'<div class="legend-item"><i style="background:' +
this.ctrl.settings.colors[0] +
'"></i> ' +
'< ' +
thresholds[0] +
'</div>';
for (let index = 0; index < thresholds.length; index += 1) {
legendHtml +=
'<div class="legend-item"><i style="background:' +
this.ctrl.settings.colors[index + 1] +
'"></i> ' +
thresholds[index] +
(thresholds[index + 1] ? '–' + thresholds[index + 1] + '</div>' : '+');
}
this.legend._div.innerHTML = legendHtml;
};
}
}
createLegend() {
this.legend = (window as any).L.control({ position: 'bottomleft' });
this.legend.onAdd = () => {
this.legend._div = (window as any).L.DomUtil.create('div', 'info legend');
this.legend.update();
return this.legend._div;
};
this.legend.update = this.getLegendUpdateFunction();
this.legend.addTo(this.map);
// Optionally display legend in different DOM element.
if (this.ctrl.settings.legendContainerSelector) {
$(this.ctrl.settings.legendContainerSelector).append(this.legend._div);
}
}
createOverlay() {
// See https://leafletjs.com/reference-1.3.4.html#imageoverlay for example usage
const latRange = this.ctrl.settings.overlayRangeLatitude
.split(',')
.slice(0, 2)
.map(x => Number(x)),
lngRange = this.ctrl.settings.overlayRangeLongitude
.split(',')
.slice(0, 2)
.map(x => Number(x));
var imageBounds = [
[latRange[0], lngRange[0]],
[latRange[1], lngRange[1]],
];
this.overlay = (window as any).L.imageOverlay(this.ctrl.settings.overlayUrl, imageBounds, {
opacity: this.ctrl.settings.overlayOpacity,
});
this.overlay.addTo(this.map);
}
needToRedrawCircles(data) {
console.info(`Data points ${data.length}. Circles on map ${this.circles.length}.`);
if (this.circles.length === 0 && data.length > 0) {
return true;
}
if (this.circles.length !== data.length) {
return true;
}
const locations = _.map(_.map(this.circles, 'options'), 'location').sort();
const dataPoints = _.map(data, 'key').sort();
return !_.isEqual(locations, dataPoints);
}
filterEmptyAndZeroValues(data) {
const countBefore = data.length;
data = _.filter(data, o => {
return !(this.ctrl.settings.hideEmpty && _.isNil(o.value)) && !(this.ctrl.settings.hideZero && o.value === 0);
});
const countAfter = data.length;
const countFiltered = countAfter - countBefore;
if (countFiltered > 0) {
console.info(`Filtered ${countFiltered} records`);
}
return data;
}
clearCircles() {
if (this.circlesLayer) {
this.circlesLayer.clearLayers();
this.removeCircles();
this.circles = [];
}
}
drawCircles() {
const data = this.filterEmptyAndZeroValues(this.ctrl.data);
if (this.needToRedrawCircles(data)) {
console.info('Creating circles');
this.clearCircles();
this.createCircles(data);
} else {
console.info('Updating circles');
this.updateCircles(data);
}
}
createCircles(data) {
console.log('createCircles: begin');
const circles: any[] = [];
const circlesByKey = {};
data.forEach(dataPoint => {
// Todo: Review: Is a "locationName" really required
// just for displaying a circle on a map?
if (!dataPoint.locationName) {
return;
}
let circle;
if (circlesByKey[dataPoint.key] === undefined) {
// Create circle.
circle = this.createCircle(dataPoint);
circles.push(circle);
circlesByKey[dataPoint.key] = circle;
} else {
// Amend popup content if circle has been created already.
circle = circlesByKey[dataPoint.key];
this.extendPopupContent(circle, dataPoint);
}
});
this.circlesLayer = this.addCircles(circles);
this.circles = circles;
console.log('createCircles: end');
}
updateCircles(data) {
const circlesByKey = {};
data.forEach(dataPoint => {
// Todo: Review: Is a "locationName" really required
// just for displaying a circle on a map?
if (!dataPoint.locationName) {
return;
}
if (circlesByKey[dataPoint.key] === undefined) {
// Update circle.
const circle = this.updateCircle(dataPoint);
if (circle) {
circlesByKey[dataPoint.key] = circle;
}
} else {
// Amend popup content if circle has been updated already.
const circle = circlesByKey[dataPoint.key];
this.extendPopupContent(circle, dataPoint);
}
});
}
createCircle(dataPoint) {
const circle = (window as any).L.circleMarker([dataPoint.locationLatitude, dataPoint.locationLongitude], {
radius: this.calcCircleSize(dataPoint.value || 0),
color: this.getColor(dataPoint),
fillColor: this.getColor(dataPoint),
fillOpacity: 0.5,
location: dataPoint.key,
stroke: Boolean(this.ctrl.settings.circleOptions.strokeEnabled),
weight: parseInt(this.ctrl.settings.circleOptions.strokeWeight, 10) || 3,
});
this.createClickthrough(circle, dataPoint);
const content = this.getPopupContent(dataPoint);
this.createPopup(circle, content);
return circle;
}
updateCircle(dataPoint) {
// Find back circle object by data point key.
const circle = _.find(this.circles, cir => {
return cir.options.location === dataPoint.key;
});
if (circle) {
circle.setRadius(this.calcCircleSize(dataPoint.value || 0));
circle.setStyle({
color: this.getColor(dataPoint),
fillColor: this.getColor(dataPoint),
fillOpacity: 0.5,
location: dataPoint.key,
});
// Re-create popup.
circle.unbindPopup();
const content = this.getPopupContent(dataPoint);
this.createPopup(circle, content);
// Re-create clickthrough-link.
this.createClickthrough(circle, dataPoint);
return circle;
}
}
calcCircleSize(dataPointValue) {
const circleMinSize = parseFloat(this.ctrl.settings.circleMinSize) || 1;
const circleMaxSize = parseFloat(this.ctrl.settings.circleMaxSize) || 10;
if (this.ctrl.settings.circleSizeAbsoluteEnabled) {
const size = dataPointValue * (parseFloat(this.ctrl.settings.circleSizeAbsoluteFactor) || 1.0);
return Math.min(circleMaxSize, Math.max(circleMinSize, size));
}
// If measurement value equals zero, use minimum circle size.
if (dataPointValue === 0) {
return circleMinSize;
}
if (this.ctrl.data.valueRange === 0) {
return circleMaxSize;
}
const dataFactor = (dataPointValue - this.ctrl.data.lowestValue) / this.ctrl.data.valueRange;
const circleSizeRange = circleMaxSize - circleMinSize;
return circleSizeRange * dataFactor + circleMinSize;
}
createClickthrough(circle, dataPoint) {
/*
* Features:
* - Unify functionality from #129 and #190
* - Generic variable interpolation from dataPoint
* - Generic variable interpolation from dashboard variables
* - Optionally open url in new window
*/
// First, use link value directly from `clickthroughUrl` setting.
let linkUrl;
if (this.ctrl.settings.clickthroughUrl) {
linkUrl = this.ctrl.settings.interpolateVariable('clickthroughUrl', dataPoint);
}
// Next, use link value from the data itself by using the
// table control option `linkField` for looking it up.
if (dataPoint.link) {
linkUrl = dataPoint.link;
// Interpolate the dashboard and dataPoint variables.
linkUrl = this.ctrl.settings.interpolateVariableValue(linkUrl, dataPoint);
}
// Deactivate all links first.
circle.off('click');
// Attach "onclick" event to data point linking.
if (linkUrl) {
const clickthroughOptions = this.ctrl.settings.clickthroughOptions;
circle.on('click', evt => {
if (clickthroughOptions && clickthroughOptions.windowName) {
window.open(linkUrl, clickthroughOptions.windowName);
} else {
window.location.assign(linkUrl);
}
});
}
}
createPopup(circle, label) {
circle.bindPopup(label, {
offset: (window as any).L.point(0, -2),
className: 'worldmap-popup',
closeButton: this.ctrl.settings.stickyLabels,
autoPan: this.ctrl.settings.autoPanLabels,
autoWidth: this.ctrl.settings.autoWidthLabels,
});
circle.on('mouseover', evt => {
const layer = evt.target;
layer.bringToFront();
circle.openPopup();
});
if (!this.ctrl.settings.stickyLabels) {
circle.on('mouseout', () => {
circle.closePopup();
});
}
}
extendPopupContent(circle, dataPoint) {
const popup = circle.getPopup();
let popupContent = popup._content;
popupContent += `\n${this.getPopupContent(dataPoint)}`;
circle.setPopupContent(popupContent);
}
getPopupContent(dataPoint) {
let unit;
let locationName = dataPoint.locationName;
let value = dataPoint.value;
if (_.isNaN(value)) {
value = 'n/a';
} else {
unit = value && value === 1 ? this.ctrl.settings.unitSingular : this.ctrl.settings.unitPlural;
}
if (this.ctrl.settings.formatOmitEmptyValue && value === 'n/a') {
return `${locationName}`.trim();
} else {
let fieldPrefix = '__field_';
let specialFields = [
fieldPrefix + this.ctrl.settings.esLocationName,
fieldPrefix + this.ctrl.settings.esMetric,
fieldPrefix + this.ctrl.settings.esGeoPoint,
];
let freeDataFields = Object.keys(dataPoint).filter(
(key: string) => key.startsWith(fieldPrefix) && !specialFields.includes(key)
);
let freeDataDisplay = freeDataFields
.map((field: string) => {
let name = field.slice(fieldPrefix.length);
let value = dataPoint[field];
return `<br />${name}: ${value}`;
})
.join('');
return `${locationName}: ${value} ${unit || ''}${freeDataDisplay}`.trim();
}
}
private getCategoryColor(label) {
for (let index = 0; index !== this.ctrl.data.categories.length; index += 1) {
if (this.ctrl.data.categories[index] === label) {
return this.ctrl.settings.colors[index + 1];
}
}
return _.first(this.ctrl.settings.colors);
}
private getThresholdColor(value) {
for (let index = this.ctrl.data.thresholds.length; index > 0; index -= 1) {
if (value >= this.ctrl.data.thresholds[index - 1]) {
return this.ctrl.settings.colors[index];
}
}
return _.first(this.ctrl.settings.colors);
}
getColor(dataPoint) {
switch (this.ctrl.settings.colorMode) {
case ColorModes.categories.id:
return this.getCategoryColor(dataPoint.locationName);
case ColorModes.threshold.id:
default:
return this.getThresholdColor(dataPoint.value);
}
}
resize() {
this.map.invalidateSize();
}
panToMapCenter(options?: any) {
console.log('panToMapCenter');
// Get a bunch of metadata from settings and data which
// controls the map centering and zoom level.
const mapDimensions = this.ctrl.settings.center;
let coordinates: LatLngExpression = [mapDimensions.mapCenterLatitude, mapDimensions.mapCenterLongitude];
let zoomLevel = mapDimensions.mapZoomLevel;
if (mapDimensions.mapFitData) {
// Choose optimal map center and zoom level based on the data points displayed.
// This is done by computing the boundaries of a Leaflet feature group created
// from the contents of the circles layer.
// https://leafletjs.com/reference-1.4.0.html#map-getboundszoom
if (this.circlesLayer) {
const group = L.featureGroup(this.circlesLayer.getLayers());
const bounds = group.getBounds();
if (!_.isEmpty(bounds)) {
coordinates = bounds.getCenter();
zoomLevel = this.map.getBoundsZoom(bounds);
}
}
} else if (mapDimensions.mapZoomByRadius) {
// Compute zoom level based on current coordinates and given radius in kilometers.
// This is done by temporarily adding a circle with the respective radius and
// computing its boundaries before removing it right away.
// Note that adding and removing a Leaflet layer to/from a map within a single
// frame will not trigger any animations, see
// https://github.com/Leaflet/Leaflet/issues/5357#issuecomment-282023917
const radius = mapDimensions.mapZoomByRadius * 1000.0;
const circle = L.circle(coordinates, { radius: radius }).addTo(this.map);
const bounds = circle.getBounds();
circle.remove();
coordinates = bounds.getCenter();
zoomLevel = this.map.getBoundsZoom(bounds);
}
zoomLevel = this.getEffectiveZoomLevel(zoomLevel);
// Apply coordinates and zoom level to Leaflet map.
this.map.setView(coordinates, zoomLevel, options);
// Resolve signal / release lock.
this.ctrl.mapCenterMoved = false;
}
removeLegend() {
this.legend.remove(this.map);
this.legend = null;
}
setMouseWheelZoom() {
if (!this.ctrl.settings.mouseWheelZoom) {
this.map.scrollWheelZoom.disable();
} else {
this.map.scrollWheelZoom.enable();
}
}
setDragging() {
if (!this.ctrl.settings.dragging) {
this.map.dragging.disable();
} else {
this.map.dragging.enable();
}
}
setDoubleClickZoom() {
if (!this.ctrl.settings.doubleClickZoom) {
this.map.doubleClickZoom.disable();
} else {
this.map.doubleClickZoom.enable();
}
}
addCircles(circles) {
// Todo: Optionally add fixed custom attributions to the circle layer.
const attribution = undefined;
return (window as any).L.layerGroup(circles, { attribution: attribution }).addTo(this.map);
}
removeCircles() {
this.map.removeLayer(this.circlesLayer);
}
setZoom(zoomFactor) {
this.map.setZoom(parseInt(zoomFactor, 10));
}
remove() {
this.circles = [];
if (this.circlesLayer) {
this.removeCircles();
}
if (this.legend) {
this.removeLegend();
}
this.map.remove();
}
drawCustomAttribution() {
// The operator wants a custom attribution.
if (this.ctrl.settings.customAttribution) {
// The custom attribution text.
const attribution = this.ctrl.settings.customAttributionText;
// Amend the Leaflet map by clearing out and setting the custom attribution text.
const attributionControl = this.map.attributionControl;
attributionControl._attributions = {};
attributionControl.addAttribution(attribution);
}
}
}