|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +from __future__ import (absolute_import, division, print_function) |
| 4 | + |
| 5 | +import json |
| 6 | + |
| 7 | +from branca.element import Figure, JavascriptLink |
| 8 | + |
| 9 | +from folium.features import GeoJson |
| 10 | + |
| 11 | +from jinja2 import Template |
| 12 | + |
| 13 | + |
| 14 | +class TimeSliderChoropleth(GeoJson): |
| 15 | + """ |
| 16 | + Creates a TimeSliderChoropleth plugin to append into a map with Map.add_child. |
| 17 | +
|
| 18 | + Parameters |
| 19 | + ---------- |
| 20 | + data: str |
| 21 | + geojson string |
| 22 | + styledict: dict |
| 23 | + A dictionary where the keys are the geojson feature ids and the values are |
| 24 | + dicts of `{time: style_options_dict}` |
| 25 | +
|
| 26 | + """ |
| 27 | + def __init__(self, data, styledict, name=None, overlay=True, control=True, **kwargs): |
| 28 | + super(TimeSliderChoropleth, self).__init__(data, name=name, overlay=overlay, control=control) |
| 29 | + if not isinstance(styledict, dict): |
| 30 | + raise ValueError('styledict must be a dictionary, got {!r}'.format(styledict)) |
| 31 | + for val in styledict.values(): |
| 32 | + if not isinstance(val, dict): |
| 33 | + raise ValueError('Each item in styledict must be a dictionary, got {!r}'.format(val)) |
| 34 | + |
| 35 | + # Make set of timestamps. |
| 36 | + timestamps = set() |
| 37 | + for feature in styledict.values(): |
| 38 | + timestamps.update(set(feature.keys())) |
| 39 | + timestamps = sorted(list(timestamps)) |
| 40 | + |
| 41 | + self.timestamps = json.dumps(timestamps) |
| 42 | + self.styledict = json.dumps(styledict, sort_keys=True, indent=2) |
| 43 | + |
| 44 | + self._template = Template(u""" |
| 45 | + {% macro script(this, kwargs) %} |
| 46 | +
|
| 47 | + var timestamps = {{ this.timestamps }}; |
| 48 | + var styledict = {{ this.styledict }}; |
| 49 | + var current_timestamp = timestamps[0]; |
| 50 | +
|
| 51 | + // insert time slider |
| 52 | + d3.select("body").insert("p", ":first-child").append("input") |
| 53 | + .attr("type", "range") |
| 54 | + .attr("width", "100px") |
| 55 | + .attr("min", 0) |
| 56 | + .attr("max", timestamps.length - 1) |
| 57 | + .attr("value", 0) |
| 58 | + .attr("id", "slider") |
| 59 | + .attr("step", "1") |
| 60 | + .style('align', 'center'); |
| 61 | +
|
| 62 | + // insert time slider output BEFORE time slider (text on top of slider) |
| 63 | + d3.select("body").insert("p", ":first-child").append("output") |
| 64 | + .attr("width", "100") |
| 65 | + .attr("id", "slider-value") |
| 66 | + .style('font-size', '18px') |
| 67 | + .style('text-align', 'center') |
| 68 | + .style('font-weight', '500%'); |
| 69 | +
|
| 70 | + var datestring = new Date(parseInt(current_timestamp)*1000).toDateString(); |
| 71 | + d3.select("output#slider-value").text(datestring); |
| 72 | +
|
| 73 | + fill_map = function(){ |
| 74 | + for (var feature_id in styledict){ |
| 75 | + let style = styledict[feature_id]//[current_timestamp]; |
| 76 | + var fillColor = 'white'; |
| 77 | + var opacity = 0; |
| 78 | + if (current_timestamp in style){ |
| 79 | + fillColor = style[current_timestamp]['color']; |
| 80 | + opacity = style[current_timestamp]['opacity']; |
| 81 | + d3.selectAll('#feature-'+feature_id |
| 82 | + ).attr('fill', fillColor) |
| 83 | + .style('fill-opacity', opacity); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | +
|
| 88 | + d3.select("#slider").on("input", function() { |
| 89 | + current_timestamp = timestamps[this.value]; |
| 90 | + var datestring = new Date(parseInt(current_timestamp)*1000).toDateString(); |
| 91 | + d3.select("output#slider-value").text(datestring); |
| 92 | + fill_map(); |
| 93 | + }); |
| 94 | +
|
| 95 | + {% if this.highlight %} |
| 96 | + {{this.get_name()}}_onEachFeature = function onEachFeature(feature, layer) { |
| 97 | + layer.on({ |
| 98 | + mouseout: function(e) { |
| 99 | + if (current_timestamp in styledict[e.target.feature.id]){ |
| 100 | + var opacity = styledict[e.target.feature.id][current_timestamp]['opacity']; |
| 101 | + d3.selectAll('#feature-'+e.target.feature.id).style('fill-opacity', opacity); |
| 102 | + } |
| 103 | + }, |
| 104 | + mouseover: function(e) { |
| 105 | + if (current_timestamp in styledict[e.target.feature.id]){ |
| 106 | + d3.selectAll('#feature-'+e.target.feature.id).style('fill-opacity', 1); |
| 107 | + } |
| 108 | + }, |
| 109 | + click: function(e) { |
| 110 | + {{this._parent.get_name()}}.fitBounds(e.target.getBounds()); |
| 111 | + } |
| 112 | + }); |
| 113 | + }; |
| 114 | +
|
| 115 | + {% endif %} |
| 116 | +
|
| 117 | + var {{this.get_name()}} = L.geoJson( |
| 118 | + {% if this.embed %}{{this.style_data()}}{% else %}"{{this.data}}"{% endif %} |
| 119 | + {% if this.smooth_factor is not none or this.highlight %} |
| 120 | + , { |
| 121 | + {% if this.smooth_factor is not none %} |
| 122 | + smoothFactor:{{this.smooth_factor}} |
| 123 | + {% endif %} |
| 124 | +
|
| 125 | + {% if this.highlight %} |
| 126 | + {% if this.smooth_factor is not none %} |
| 127 | + , |
| 128 | + {% endif %} |
| 129 | + onEachFeature: {{this.get_name()}}_onEachFeature |
| 130 | + {% endif %} |
| 131 | + } |
| 132 | + {% endif %} |
| 133 | + ).addTo({{this._parent.get_name()}} |
| 134 | + ); |
| 135 | +
|
| 136 | + {{this.get_name()}}.setStyle(function(feature) {feature.properties.style;}); |
| 137 | +
|
| 138 | + {{ this.get_name() }}.eachLayer(function (layer) { |
| 139 | + layer._path.id = 'feature-' + layer.feature.id; |
| 140 | + }); |
| 141 | +
|
| 142 | + d3.selectAll('path') |
| 143 | + .attr('stroke', 'white') |
| 144 | + .attr('stroke-width', 0.8) |
| 145 | + .attr('stroke-dasharray', '5,5') |
| 146 | + .attr('fill-opacity', 0); |
| 147 | + fill_map(); |
| 148 | +
|
| 149 | + {% endmacro %} |
| 150 | + """) |
| 151 | + |
| 152 | + def render(self, **kwargs): |
| 153 | + super(TimeSliderChoropleth, self).render(**kwargs) |
| 154 | + figure = self.get_root() |
| 155 | + assert isinstance(figure, Figure), ('You cannot render this Element ' |
| 156 | + 'if it is not in a Figure.') |
| 157 | + figure.header.add_child(JavascriptLink('https://d3js.org/d3.v4.min.js'), name='d3v4') |
0 commit comments