Repository navigation
Expand file tree
/
Copy pathleaflet.js
More file actions
504 lines (453 loc) · 14.8 KB
/
Copy pathleaflet.js
File metadata and controls
504 lines (453 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
import * as d3 from 'd3';
var L = require('leaflet');
import * as topojson from 'topojson';
/**
* Leaflet Chart
* Creates a map using Leaflet.js
*/
export default function (config, helper) {
var Leaflet = Object.create(helper);
Leaflet.init = function (config) {
const vm = this;
vm._config = config ? config : {};
vm._scales = {};
vm._axes = {};
vm._data = [];
vm._scales.color = d3
.scaleQuantize()
.range(['#fee5d9', '#fcae91', '#fb6a4a', '#de2d26', '#a50f15']);
};
Leaflet.id = function (col) {
var vm = this;
vm._config.id = col;
return vm;
};
Leaflet.fill = function (col) {
var vm = this;
vm._config.fill = col;
return vm;
};
Leaflet.opacity = function (value) {
var vm = this;
vm._config.opacity = value;
return vm;
};
Leaflet.colors = function (colors) {
var vm = this;
vm._config.colors = colors;
if (colors && Array.isArray(colors)) {
vm._scales.color.range(colors);
} else if (typeof colors === 'function') {
vm._scales.color = colors;
}
return vm;
};
/**
* Value labels on each region: off by default. When on, a label that would
* sit on another is left out (larger regions first).
* @param {boolean} on
*/
Leaflet.labels = function (on) {
var vm = this;
vm._config.labels = on !== false;
return vm;
};
Leaflet.colorLegend = function (legendTitle) {
var vm = this;
vm._config.legendTitle = legendTitle;
return vm;
};
// -------------------------------
// Triggered by chart.js;
Leaflet.data = function (data) {
var vm = this;
vm._topojson = data[1] ? data[1] : false; //Topojson
data = data[0]; //User data
if (vm._config.data.filter) {
data = data.filter(vm._config.data.filter);
}
vm._data = data;
//vm._quantiles = vm._setQuantile(data);
vm._minMax = d3.extent(data, function (d) {
return +d[vm._config.fill];
});
// Round class breaks (0–1,200–2,400…) rather than the data's extremes.
vm._scales.color.domain(vm._minMax);
if (vm._scales.color.nice) vm._scales.color.nice();
var objects = vm._config.map.topojson.objects;
vm._nodes = [];
if (Array.isArray(objects)) {
for (let idx = 0; idx < objects.length; idx++) {
const obj = objects[idx];
vm._topojson.objects[obj].geometries.forEach(function (geom) {
geom.id = vm._config.map.topojson.parser(geom);
var found = vm._data.filter((o) => o[vm._config.id] == geom.id)[0];
if (found) {
geom.properties[vm._config.fill] = found[vm._config.fill];
}
vm._nodes.push(geom);
});
}
} else if (objects) {
vm._topojson.objects[objects].geometries.forEach(function (geom) {
geom.id = vm._config.map.topojson.parser(geom);
var found = vm._data.filter((o) => o[vm._config.id] == geom.id)[0];
if (found) {
geom.properties[vm._config.fill] = found[vm._config.fill];
}
vm._nodes.push(geom);
});
}
// vm._config.map.min = vm._minMax[0];
// vm._config.map.max = vm._minMax[1];
return vm;
};
Leaflet.scales = function () {
var vm = this;
return vm;
};
Leaflet.drawColorLegend = function () {
var vm = this;
var range = vm._scales.color.range().length;
var step = (vm._minMax[1] - vm._minMax[0]) / (range - 1);
var domain = vm._config.colors;
var quantilePosition = d3
.scaleBand()
.rangeRound([vm._config.size.height * 0.8, 0])
.domain(domain);
//Add gradient legend
//defaults to right position
var legend = d3
.select('#' + vm._config.bindTo)
.append('svg')
.attr('width', 120)
.attr('height', vm._config.size.height)
.style('z-index', 401)
.style('position', 'absolute')
.style('top', '4px')
.style('right', '2px')
.append('g')
.attr('class', 'legend quantized')
.attr('transform', 'translate(50,25)');
// A translucent panel in the page's surface colour: the key stays
// legible where it sits over the map, and the map still shows through.
// (On a phone it covers part of the map; a key outside the map needs
// room from the host's layout.)
legend
.append('rect')
.attr('class', 'legend-background')
.attr('x', -50)
.attr('y', -25)
.attr('width', 118)
.attr('height', vm._config.size.height * 0.8 + 40)
.attr('rx', 4)
.style('fill', 'var(--dbox-surface, Canvas)')
.style('opacity', 0.6);
// legend title, wrapped to the legend's width
legend
.append('text')
.attr('x', -45)
.attr('y', -12)
.attr('class', 'legend-title')
.attr('text-anchor', 'start')
.attr('font-size', 12)
.style('font-weight', 600)
.style('fill', 'var(--dbox-text, currentColor)')
.text(vm._config.legendTitle)
.call(vm.utils.wrap, 110);
// A title on two lines pushes the swatches down, never itself up and out.
var titleLines = legend.selectAll('.legend-title tspan').size() || 1;
var extra = (titleLines - 1) * 13;
legend.attr('transform', 'translate(50,' + (25 + extra) + ')');
legend.select('.legend-title').attr('transform', 'translate(0,' + -extra + ')');
legend
.select('.legend-background')
.attr('y', -25 - extra)
.attr('height', vm._config.size.height * 0.8 + 40 + extra);
var quantiles = legend
.selectAll('.quantile')
.data(vm._config.colors)
.enter()
.append('g')
.attr('class', 'quantile')
.attr('transform', function (d) {
return 'translate(-20, ' + quantilePosition(d) + ')';
});
// Rect
quantiles
.append('rect')
.attr('x', -10)
.attr('y', 0)
.attr('width', 18)
.attr('height', quantilePosition.bandwidth())
.attr('fill', function (d) {
return d;
});
//top text is the max value
quantiles
.append('text')
.attr('x', 17)
.attr('y', 5)
.attr('class', 'top-label')
.attr('text-anchor', 'start')
.attr('font-size', 11)
.style('font-variant-numeric', 'tabular-nums')
.style('fill', 'var(--dbox-text-secondary, color-mix(in srgb, currentColor 72%, transparent))')
.text(function (d) {
let max = vm._scales.color.invertExtent(d)[1];
// A host's cap on the top class (e.g. 100 for percentages).
if (vm._config.map.max !== undefined && max > vm._config.map.max) {
max = vm._config.map.max;
}
if (vm._config.map.formatLegend) {
return vm._config.map.formatLegend(max);
} else {
return vm.utils.format()(max);
}
});
//bottom text is the min value
quantiles
.append('text')
.attr('x', 17)
.attr('y', vm._config.size.height / 5 - 11)
.attr('class', 'bottom-label')
.attr('text-anchor', 'start')
.attr('font-size', 11)
.style('font-variant-numeric', 'tabular-nums')
.style('fill', 'var(--dbox-text-secondary, color-mix(in srgb, currentColor 72%, transparent))')
.text(function (d, i) {
if (i === 0) {
let min = vm._scales.color.invertExtent(d)[0];
if (vm._config.map.formatLegend) {
return vm._config.map.formatLegend(min);
} else {
return vm.utils.format()(min);
}
} else {
return '';
}
});
};
Leaflet.draw = function () {
var vm = this;
var urlTopojson = vm._config.map.topojson.url;
var objects = vm._config.map.topojson.objects; //'states'
var tran = vm._config.map.topojson.translate; //var tran = [2580, 700];
var scale = vm._config.map.topojson.scale; //1300
var parser = vm._config.map.topojson.parser;
var id = vm._config.map.topojson.id;
L.TopoJSON = L.GeoJSON.extend({
addData: function (jsonData) {
var geojson, key;
if (jsonData.type === 'Topology') {
if (objects) {
if (Array.isArray(objects)) {
for (let idx = 0; idx < objects.length; idx++) {
const obj = objects[idx];
geojson = topojson.feature(jsonData, jsonData.objects[obj]);
L.GeoJSON.prototype.addData.call(this, geojson);
}
} else {
geojson = topojson.feature(jsonData, jsonData.objects[objects]);
L.GeoJSON.prototype.addData.call(this, geojson);
}
} else {
for (key in jsonData.objects) {
geojson = topojson.feature(jsonData, jsonData.objects[key]);
L.GeoJSON.prototype.addData.call(this, geojson);
}
}
} else {
L.GeoJSON.prototype.addData.call(this, jsonData);
}
},
});
var LatLng = {
lat: 25.5629994,
lon: -100.6405644,
};
if (
vm._config.map.topojson.center &&
vm._config.map.topojson.center.length === 2
) {
LatLng.lat = vm._config.map.topojson.center[0];
LatLng.lon = vm._config.map.topojson.center[1];
}
var bounds = new L.LatLngBounds(
new L.LatLng(LatLng.lat + 5, LatLng.lon - 5),
new L.LatLng(LatLng.lat - 5, LatLng.lon + 5)
);
vm._map = new L.Map(vm._config.bindTo, {
center: bounds.getCenter(),
zoom: vm._config.map.topojson.zoom || 7,
maxZoom: vm._config.map.topojson.maxZoom || 10,
minZoom: vm._config.map.topojson.minZoom || 3,
maxBounds: bounds,
maxBoundsViscosity: 1.0,
});
// Leaflet's stylesheet gives the map Helvetica; take the page's font.
vm._map.getContainer().style.fontFamily = 'inherit';
vm.utils.ensureSurface(vm._map.getContainer(), vm._map.getContainer());
// Basemap: map.tiles is a tile URL template, or false for none. The
// default is the same OpenStreetMap France style as before, over https
// so it also loads on https pages.
var tiles = vm._config.map.tiles;
if (tiles !== false) {
L.tileLayer(
typeof tiles === 'string'
? tiles
: 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png',
{
attribution:
vm._config.map.tilesAttribution ||
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}
).addTo(vm._map);
}
var topoLayer = new L.TopoJSON();
addTopoData(vm._topojson);
// vm._map.on('zoomend', function() {
// d3.selectAll('.dbox-label').remove();
// Object.values(vm._map._layers)
// .filter(obj => obj.feature)
// .forEach(function(layer) {
// vm.drawLabel(layer);
// });
// });
function addTopoData(topoData) {
topoLayer.addData(topoData);
topoLayer.addTo(vm._map);
topoLayer.eachLayer(handleLayer);
if (vm._config.labels) vm.drawLabels(topoLayer);
}
var tip = vm.utils.d3.tip().html(
vm._config.tip
? vm._config.tip.bind(this)
: function (d) {
let html =
'<div class="d3-tip" style="z-index: 99999;"><span>' +
regionName(d.feature.properties) +
'</span><br/><span>' +
vm.utils.format()(d.feature.properties[vm._config.fill]) +
'</span></div>';
return html;
}
);
d3.select('#' + vm._config.bindTo)
.select('svg.leaflet-zoom-animated')
.call(tip);
function regionName(props) {
if (typeof vm._config.map.name === 'function') return vm._config.map.name(props);
return props.NOM_ENT || props.NOM_MUN || props.name || props.state_name || props.NAME || '';
}
/**
* Set each layer
* @param {obj} layer
*/
function handleLayer(layer) {
var value = layer.feature.properties[vm._config.fill];
if (!value) {
// Remove polygons without data
/** @todo validate what to do with NA's */
d3.select(layer._path).remove();
} else {
var fillColor = vm._scales.color(value);
layer.setStyle({
fillColor: fillColor,
fillOpacity: vm._config.opacity || 0.7,
weight: 1,
opacity: 1,
});
d3.select(layer._path).style('stroke', 'var(--dbox-surface, Canvas)');
layer.on({
mouseover: function () {
enterLayer(layer);
},
mouseout: function () {
leaveLayer(layer);
},
});
}
}
function enterLayer(layer) {
tip.show(layer, d3.select(layer._path).node());
}
function leaveLayer(layer) {
tip.hide(layer);
}
/**
* Draw Legend
*/
if (typeof vm._config.legend === 'function') {
vm._config.legend.call(this, vm._nodes);
}
Leaflet.drawColorLegend();
return vm;
};
/**
* Value labels, larger regions first; a label that would overlap one
* already placed is left out (the tooltip still has it).
* @param {L.Layer} group the regions
*/
Leaflet.drawLabels = function (group) {
const vm = this;
const layers = [];
group.eachLayer(function (layer) {
if (layer._path && layer.feature.properties[vm._config.fill] !== undefined) {
const box = layer._path.getBBox();
layers.push({ layer: layer, box: box, area: box.width * box.height });
}
});
layers.sort(function (a, b) {
return b.area - a.area;
});
const placed = [];
layers.forEach(function (item) {
const node = vm.drawLabel(item.layer, item.box);
if (!node) return;
const r = node.getBBox();
const hit = placed.some(function (p) {
return r.x < p.x + p.width + 2 && r.x + r.width + 2 > p.x && r.y < p.y + p.height && r.y + r.height > p.y;
});
if (hit) {
node.remove();
} else {
placed.push(r);
}
});
return vm;
};
/**
* One region's value label, with a halo in the page's surface colour so it
* reads on any fill.
* @returns {SVGTextElement|null}
*/
Leaflet.drawLabel = function (layer, bbox) {
const vm = this;
const props = layer.feature.properties;
bbox = bbox || layer._path.getBBox();
var svg = d3
.select('#' + vm._config.bindTo)
.select('svg.leaflet-zoom-animated');
if (props[vm._config.fill] === undefined) return null;
return svg
.append('text')
.attr('class', 'dbox-label')
.attr('x', bbox.x + bbox.width / 2)
.attr('y', bbox.y + d3.min([bbox.height / 2, 30]))
.attr('text-anchor', 'middle')
.attr('font-size', 11)
.style('fill', 'var(--dbox-text, currentColor)')
.style('stroke', 'var(--dbox-surface, Canvas)')
.style('stroke-width', 3)
.style('paint-order', 'stroke')
.style('pointer-events', 'none')
.text(
(props[vm._config.poly_name] ? props[vm._config.poly_name] + ': ' : '') +
vm.utils.format()(props[vm._config.fill])
)
.node();
};
Leaflet.init(config);
return Leaflet;
}