Skip to content
Closed
230 changes: 152 additions & 78 deletions examples/GeoJSON_and_choropleth.ipynb

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions folium/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
CustomIcon,
DivIcon,
GeoJson,
GeoJsonStyleMap,
GeoJsonStylePropertyFunction,
GeoJsonTooltip,
LatLngPopup,
RegularPolygonMarker,
Expand Down Expand Up @@ -76,6 +78,8 @@
'Figure',
'FitBounds',
'GeoJson',
'GeoJsonStyleMap',
'GeoJsonStylePropertyFunction',
'GeoJsonTooltip',
'Html',
'IFrame',
Expand Down
149 changes: 128 additions & 21 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ class GeoJson(Layer):
* If dict, then data will be converted to JSON and embedded
in the JavaScript.
* If str, then data will be passed to the JavaScript as-is.
style_function: function, default None
style_function: GeoJsonStyleFunction or function, default None
Function mapping a GeoJson Feature to a style dict.
highlight_function: function, default None
Function mapping a GeoJson Feature to a style dict for mouse events.
Expand Down Expand Up @@ -416,7 +416,6 @@ class GeoJson(Layer):
{%- endif %}
}
).addTo({{ this._parent.get_name()}} );
{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});
{% endmacro %}
""") # noqa

Expand Down Expand Up @@ -446,14 +445,20 @@ def __init__(self, data, style_function=None, name=None,
else:
raise ValueError('Cannot render objects with any missing geometries. {!r}'.format(data))

self.style_function = style_function or (lambda x: {})

self.highlight = highlight_function is not None
self.highlight_function = highlight_function or (lambda x: {})

self.smooth_factor = smooth_factor

self._validate_function(self.style_function, 'style_function')
if isinstance(style_function, GeoJsonStyleFunction):
self.add_child(style_function)
self.should_style_data = False
else:
self.style_function = style_function or (lambda x: {})
self._validate_function(self.style_function, 'style_function')
self.add_child(GeoJsonStylePropertyFunction())
self.should_style_data = True

self._validate_function(self.highlight_function, 'highlight_function')

if isinstance(tooltip, (GeoJsonTooltip, Tooltip)):
Expand Down Expand Up @@ -489,21 +494,22 @@ def style_data(self):
self.data = {'type': 'Feature', 'geometry': self.data}
self.data = {'type': 'FeatureCollection', 'features': [self.data]}

for feature in self.data['features']:
feature_style = self.style_function(feature)
for key, value in feature_style.items():
if isinstance(value, MacroElement):
# Make sure objects are rendered:
if value._parent is None:
value._parent = self
value.render()
# Replace objects with their Javascript var names:
feature_style[key] = "{{'" + value.get_name() + "'}}"

feature.setdefault('properties', {}).setdefault('style', {}) \
.update(feature_style)
feature.setdefault('properties', {}).setdefault('highlight', {}) \
.update(self.highlight_function(feature))
if self.should_style_data:
for feature in self.data['features']:
feature_style = self.style_function(feature)
for key, value in feature_style.items():
if isinstance(value, MacroElement):
# Make sure objects are rendered:
if value._parent is None:
value._parent = self
value.render()
# Replace objects with their Javascript var names:
feature_style[key] = "{{'" + value.get_name() + "'}}"

feature.setdefault('properties', {}).setdefault('style', {}) \
.update(feature_style)
feature.setdefault('properties', {}).setdefault('highlight', {}) \
.update(self.highlight_function(feature))

data_json = json.dumps(self.data, sort_keys=True)
# Remove quotes around Jinja2 template expressions:
Expand Down Expand Up @@ -626,7 +632,6 @@ def style_data(self):
a corresponding JSON output.

"""

def recursive_get(data, keys):
if len(keys):
return recursive_get(data.get(keys[0]), keys[1:])
Expand Down Expand Up @@ -814,6 +819,108 @@ def render(self, **kwargs):
super(GeoJsonTooltip, self).render(**kwargs)


class GeoJsonStyleFunction(MacroElement):
"""
Base class for style functions that generate JS functions

This class should not be used directly. A class extending this one should provide an attribute named
`_function_template`, which should be a Template object with source of the form:

function(feature) {
...
}
"""

_template = Template(u"""
{% macro script(this, kwargs) %}
{{ this._parent.get_name() }}.setStyle({{ this._function_template.render(this=this, kwargs=kwargs) }});
{% endmacro %}
""") # noqa


class GeoJsonStylePropertyFunction(GeoJsonStyleFunction):
_function_template = Template(u"""
function(feature) {
var style = {{this.default}};
return Object.assign(style, feature.properties.{{this.property_name}});
}
""") # noqa

def __init__(self, property_name='style', default=None):
"""
Style function that retrieves the style dictionary from a property in the GeoJson data

This class can be used if the styling is embedded in the GeoJson data directly, for instance (using the default
property name 'style'):

{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"style": { "color": "#ff0000" }
},
"geometry": {
"type": "LineString",
"coordinates": [[-105, 40], [-110, 45], [-115, 55]]
}
}]
}


Parameters
----------
property_name: str, default 'style'
The name of the feature property that the style is stored in
default: dict, default None
If provided, use this style as the base, and extend/override style elements with those stored in the
feature attribute
"""
super(GeoJsonStylePropertyFunction, self).__init__()
self._name = "GeoJsonStylePropertyFunction"
self.property_name = property_name
self.default = json.dumps(default) if default is not None else '{}'


class GeoJsonStyleMap(GeoJsonStyleFunction):
_function_template = Template(u"""
function(feature) {
var style = {{this.default}}
var val = feature.properties.{{this.property_name}};
{% for key in this.style_map %}
if (val == {{key}}) { return Object.assign(style, {{this.style_map[key]}}); }
{% endfor %}
return style;
}
""") # noqa

def __init__(self, property_name, style_map, default=None):
"""
Style function that maps feature property values to a style

This class is most useful if the styling should be determined based on the value of a single property that
has a limited number of unique values, or where only for a small number of values a special style should be used
and a default style can be used for all other values. When the property can have many different values, with the
worst case being that each feature has a unique value, this class has little to no benfiti, and you should
consider using a plain style function instead.

Parameters
----------
property_name: str
The property whose values are used as keys in the style map
style_map: dict
Dictionary that should map values of the feature property to style dictionaries
default: dict, default None
If provided, use this style as the base, and extend/override style elements with those stored in the
feature attribute
"""
super(GeoJsonStyleMap, self).__init__()
self._name = "GeoJsonStyleMap"
self.property_name = property_name
self.style_map = {json.dumps(k): json.dumps(style_map[k]) for k in style_map}
self.default = json.dumps(default) if default is not None else '{}'


class Choropleth(FeatureGroup):
"""Apply a GeoJSON overlay to the map.

Expand Down
24 changes: 24 additions & 0 deletions tests/test_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ def test_get_vegalite_major_version():

assert vegalite_no_version._get_vegalite_major_versions(spec_no_version) is None


# GeoJsonTooltip GeometryCollection
def test_geojson_tooltip():
m = folium.Map([30.5, -97.5], zoom_start=10)
Expand All @@ -204,3 +205,26 @@ def test_geojson_tooltip():
warnings.simplefilter('always')
m._repr_html_()
assert issubclass(w[-1].category, UserWarning), "GeoJsonTooltip GeometryCollection test failed."


# GeoJsonStylePropertyFunction
def test_geojson_style_property_function():
m = folium.Map([30.5, -97.5], zoom_start=10)
folium.GeoJson(os.path.join(rootpath, "kuntarajat.geojson"),
style_function=folium.GeoJsonStylePropertyFunction(
property_name='foo',
default={'color': '#ff0000'})
).add_to(m)
m._repr_html_()


# GeoJsonStyleMap
def test_geojson_style_map():
m = folium.Map([30.5, -97.5], zoom_start=10)
folium.GeoJson(os.path.join(rootpath, "kuntarajat.geojson"),
style_function=folium.GeoJsonStyleMap(
property_name='code',
style_map={'area005': {'color': '#00ff00'}},
default={'color': '#ff0000'})
).add_to(m)
m._repr_html_()