"
],
"text/plain": [
- ""
+ ""
]
},
"execution_count": 7,
@@ -291,6 +290,63 @@
"m"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When you only have a small number of different styles for possibly many different features, like in this example, you can use a `GeoJsonStyleMap`, which reduces the duplication of styles in the output and as such can make the data size of the final map significantly smaller."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {
+ "scrolled": false
+ },
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
],
"text/plain": [
- ""
+ ""
]
},
- "execution_count": 21,
+ "execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
@@ -908,7 +982,7 @@
"\n",
"folium.LayerControl(collapsed=False).add_to(m)\n",
"\n",
- "m.save(os.path.join('results', 'GeoJSON_and_choropleth_11.html'))\n",
+ "m.save(os.path.join('results', 'GeoJSON_and_choropleth_15.html'))\n",
"\n",
"m"
]
@@ -930,7 +1004,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.6.1"
+ "version": "3.6.7"
},
"toc": {
"base_numbering": 1,
diff --git a/folium/__init__.py b/folium/__init__.py
index 3ed03f9fdf..1636940a11 100644
--- a/folium/__init__.py
+++ b/folium/__init__.py
@@ -27,6 +27,8 @@
CustomIcon,
DivIcon,
GeoJson,
+ GeoJsonStyleMap,
+ GeoJsonStylePropertyFunction,
GeoJsonTooltip,
LatLngPopup,
RegularPolygonMarker,
@@ -76,6 +78,8 @@
'Figure',
'FitBounds',
'GeoJson',
+ 'GeoJsonStyleMap',
+ 'GeoJsonStylePropertyFunction',
'GeoJsonTooltip',
'Html',
'IFrame',
diff --git a/folium/features.py b/folium/features.py
index 4d54e7e700..f56759be69 100644
--- a/folium/features.py
+++ b/folium/features.py
@@ -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.
@@ -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
@@ -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)):
@@ -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:
@@ -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:])
@@ -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.
diff --git a/tests/test_features.py b/tests/test_features.py
index 40bc494d37..31a3468a70 100644
--- a/tests/test_features.py
+++ b/tests/test_features.py
@@ -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)
@@ -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_()