|
| 1 | +//Legend code adapted from http://leafletjs.com/examples/choropleth.html |
| 2 | +dc_leaflet.legend = function() { |
| 3 | + var _parent, _legend = {}; |
| 4 | + var _Llegend = L.control({position: 'bottomleft'}); |
| 5 | + |
| 6 | + _legend.parent = function (parent) { |
| 7 | + if(!arguments.length) |
| 8 | + return _parent; |
| 9 | + _parent = parent; |
| 10 | + return this; |
| 11 | + }; |
| 12 | + |
| 13 | + _legend.render = function () { |
| 14 | + return _legend.redraw(); |
| 15 | + }; |
| 16 | + |
| 17 | + _legend.redraw = function () { |
| 18 | + _Llegend.update(); |
| 19 | + return _legend; |
| 20 | + }; |
| 21 | + |
| 22 | + _legend.leafletLegend = function () { |
| 23 | + return _Llegend; |
| 24 | + }; |
| 25 | + |
| 26 | + _Llegend.onAdd = function (map) { |
| 27 | + this._div = L.DomUtil.create('div', 'info legend'); |
| 28 | + this.update(); |
| 29 | + return this._div; |
| 30 | + }; |
| 31 | + |
| 32 | + _Llegend.update = function () { |
| 33 | + var i, minValue, maxValue, palette, colorLength, delta, grades; |
| 34 | + if (_parent.colorDomain()) {//check because undefined for marker charts |
| 35 | + minValue = _parent.colorDomain()[0]; |
| 36 | + maxValue = _parent.colorDomain()[1]; |
| 37 | + palette = _parent.colors().range(); |
| 38 | + colorLength = _parent.colors().range().length; |
| 39 | + delta = (maxValue - minValue)/colorLength; |
| 40 | + |
| 41 | + //define grades for legend colours |
| 42 | + //based on equation in dc.js colorCalculator (before verion based on colorMixin) |
| 43 | + grades = []; |
| 44 | + grades[0] = minValue; |
| 45 | + for (i= 1; i < colorLength; i++) { |
| 46 | + grades[i] = Math.round((0.5 + (i - 1)) * delta + minValue); |
| 47 | + } |
| 48 | + |
| 49 | + var div = L.DomUtil.create('div', 'info legend'), |
| 50 | + labels = []; |
| 51 | + |
| 52 | + // loop through our density intervals and generate a label with a colored square for each interval |
| 53 | + this._div.innerHTML = ""; //reset so that legend is not plotted multiple times |
| 54 | + for (i = 0; i < grades.length; i++) { |
| 55 | + this._div.innerHTML += |
| 56 | + '<i style="background:' + palette[i] + '"></i> ' + |
| 57 | + grades[i] + (grades[i + 1] ? '–' + grades[i + 1] + '<br>' : '+'); |
| 58 | + } |
| 59 | + } |
| 60 | + }; |
| 61 | + return _legend; |
| 62 | +}; |
0 commit comments