Skip to content

Commit ef07968

Browse files
author
Martin Journois
committed
Add GeoJsonStyle for choropleth
1 parent 5a4bf93 commit ef07968

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

folium/features.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import json
1515

1616
from .six import text_type, binary_type, urlopen
17+
from .utilities import color_brewer
1718

1819
def _camelify(out):
1920
return (''.join(["_"+x.lower() if i<len(out)-1 and x.isupper() and out[i+1].islower()
@@ -970,6 +971,57 @@ def __init__(self, data):
970971
{% endmacro %}
971972
""")
972973

974+
class GeoJsonStyle(MacroElement):
975+
def __init__(self, color_domain, color_code, color_data=None, key_on='feature.properties.color'):
976+
"""TODO : docstring here.
977+
"""
978+
super(GeoJsonStyle, self).__init__()
979+
self._name = 'GeoJsonStyle'
980+
981+
self.color_domain = color_domain
982+
self.color_range = color_brewer(color_code, n=len(color_domain))
983+
self.color_data = json.dumps(color_data)
984+
self.key_on = key_on
985+
986+
self._template = Template(u"""
987+
{% macro script(this, kwargs) %}
988+
var {{this.get_name()}} = {
989+
color_scale : d3.scale.threshold()
990+
.domain({{this.color_domain}})
991+
.range({{this.color_range}}),
992+
color_data : {{this.color_data}},
993+
color_function : function(feature) {
994+
{% if this.color_data=='null' %}
995+
return this.color_scale({{this.key_on}});
996+
{% else %}
997+
return this.color_scale(this.color_data[{{this.key_on}}]);
998+
{% endif %}
999+
},
1000+
};
1001+
1002+
{{this._parent.get_name()}}.setStyle(function(feature) {
1003+
return {
1004+
fillColor: {{this.get_name()}}.color_function(feature),
1005+
weight: 2,
1006+
opacity: 1,
1007+
color: 'white',
1008+
dashArray: '3',
1009+
fillOpacity: 0.7
1010+
};
1011+
});
1012+
{% endmacro %}
1013+
""")
1014+
def render(self,**kwargs):
1015+
super(GeoJsonStyle,self).render(**kwargs)
1016+
1017+
figure = self.get_root()
1018+
assert isinstance(figure,Figure), ("You cannot render this Element "
1019+
"if it's not in a Figure.")
1020+
1021+
figure.header.add_children(\
1022+
JavascriptLink("https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"),
1023+
name='d3')
1024+
9731025
class MarkerCluster(MacroElement):
9741026
"""Adds a MarkerCluster layer on the map."""
9751027
def __init__(self):

0 commit comments

Comments
 (0)