diff --git a/examples/GeoJSON_and_choropleth.ipynb b/examples/GeoJSON_and_choropleth.ipynb index 7bdc1f695c..7a9143ee28 100644 --- a/examples/GeoJSON_and_choropleth.ipynb +++ b/examples/GeoJSON_and_choropleth.ipynb @@ -9,7 +9,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "0.6.0+159.g84a27d0.dirty\n" + "0.7.0+19.g7a1fe3c.dirty\n" ] } ], @@ -17,6 +17,7 @@ "import os\n", "import folium\n", "\n", + "\n", "print(folium.__version__)" ] }, @@ -38,9 +39,7 @@ { "cell_type": "code", "execution_count": 2, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [], "source": [ "import json\n", @@ -97,10 +96,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 3, @@ -133,10 +132,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 4, @@ -169,10 +168,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 5, @@ -191,7 +190,7 @@ " gdf,\n", ").add_to(m)\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_3.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_2.html'))\n", "\n", "m" ] @@ -218,10 +217,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 6, @@ -262,10 +261,10 @@ { "data": { "text/html": [ - "
" + "
" ], "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": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "m = folium.Map([43, -100], zoom_start=4)\n", + "\n", + "for feature in geo_json_data['features']:\n", + " feature['properties']['has_e'] = 'e' in feature['properties']['name'].lower()\n", + " \n", + "style_map = folium.GeoJsonStyleMap(\n", + " property_name='has_e',\n", + " style_map={\n", + " True: {\n", + " 'fillColor': 'green'\n", + " }},\n", + " default={\n", + " 'fillColor': '#ffff00',\n", + " 'color': 'black',\n", + " 'weight': 2,\n", + " 'dashArray': '5, 5'\n", + " })\n", + "\n", + "folium.GeoJson(\n", + " geo_json_data,\n", + " style_function=style_map\n", + ").add_to(m)\n", + "\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_5.html'))\n", + "\n", + "m" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -304,7 +360,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 9, "metadata": { "scrolled": true }, @@ -313,6 +369,19 @@ "data": { "text/html": [ "
\n", + "\n", "\n", " \n", " \n", @@ -360,7 +429,7 @@ "4 CA 10.1" ] }, - "execution_count": 8, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } @@ -384,7 +453,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 10, "metadata": {}, "outputs": [ { @@ -400,10 +469,10 @@ "3.210.3" ], "text/plain": [ - "" + "" ] }, - "execution_count": 9, + "execution_count": 10, "metadata": {}, "output_type": "execute_result" } @@ -429,16 +498,16 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "7.0999999999999996" + "7.1" ] }, - "execution_count": 10, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } @@ -458,19 +527,19 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 11, + "execution_count": 12, "metadata": {}, "output_type": "execute_result" } @@ -492,7 +561,7 @@ "\n", "folium.LayerControl().add_to(m)\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_5.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_6.html'))\n", "\n", "m" ] @@ -506,10 +575,8 @@ }, { "cell_type": "code", - "execution_count": 12, - "metadata": { - "collapsed": true - }, + "execution_count": 13, + "metadata": {}, "outputs": [], "source": [ "color_dict = {key: colormap(unemployment_dict[key]) for key in unemployment_dict.keys()}" @@ -517,19 +584,19 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 13, + "execution_count": 14, "metadata": {}, "output_type": "execute_result" } @@ -548,11 +615,18 @@ " }\n", ").add_to(m)\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_6.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_7.html'))\n", "\n", "m" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using `GeoJsonStyleMap` is much more efficient if only a small amount of different styles is used (" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -562,19 +636,19 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 14, + "execution_count": 15, "metadata": {}, "output_type": "execute_result" } @@ -583,7 +657,7 @@ "colormap.caption = 'Unemployment color scale'\n", "colormap.add_to(m)\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_7.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_8.html'))\n", "\n", "m" ] @@ -601,19 +675,19 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 15, + "execution_count": 16, "metadata": {}, "output_type": "execute_result" } @@ -628,7 +702,7 @@ " line_weight=2,\n", ").add_to(m)\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_7.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_9.html'))\n", "\n", "m" ] @@ -642,19 +716,19 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 16, + "execution_count": 17, "metadata": {}, "output_type": "execute_result" } @@ -664,7 +738,7 @@ "\n", "folium.Choropleth(geo_data=us_states).add_to(m)\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_8.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_10.html'))\n", "\n", "m" ] @@ -678,19 +752,19 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 17, + "execution_count": 18, "metadata": {}, "output_type": "execute_result" } @@ -707,7 +781,7 @@ ").add_to(m)\n", "\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_9.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_11.html'))\n", "\n", "m" ] @@ -721,19 +795,19 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 18, + "execution_count": 19, "metadata": {}, "output_type": "execute_result" } @@ -751,7 +825,7 @@ ").add_to(m)\n", "\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_10.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_12.html'))\n", "\n", "m" ] @@ -765,7 +839,7 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 20, "metadata": { "scrolled": false }, @@ -773,13 +847,13 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 19, + "execution_count": 20, "metadata": {}, "output_type": "execute_result" } @@ -800,7 +874,7 @@ " highlight=True\n", ").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_13.html'))\n", "\n", "m" ] @@ -814,7 +888,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 21, "metadata": { "scrolled": false }, @@ -822,13 +896,13 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 20, + "execution_count": 21, "metadata": {}, "output_type": "execute_result" } @@ -850,7 +924,7 @@ ").add_to(m)\n", "\n", "\n", - "m.save(os.path.join('results', 'GeoJSON_and_choropleth_10.html'))\n", + "m.save(os.path.join('results', 'GeoJSON_and_choropleth_14.html'))\n", "\n", "m" ] @@ -864,7 +938,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 22, "metadata": {}, "outputs": [ { @@ -878,13 +952,13 @@ { "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_()