From a35b619754310654f058a9e8239e753de9ce0fdb Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Fri, 28 Dec 2018 17:05:45 +0100 Subject: [PATCH 1/9] Add GeoJsonStyleMap class to make small nr of styles more efficient --- folium/__init__.py | 2 ++ folium/features.py | 45 ++++++++++++++++++++++++++++++++++++--------- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/folium/__init__.py b/folium/__init__.py index 3ed03f9fdf..64cd39ad9c 100644 --- a/folium/__init__.py +++ b/folium/__init__.py @@ -28,6 +28,7 @@ DivIcon, GeoJson, GeoJsonTooltip, + GeoJsonStyleMap, LatLngPopup, RegularPolygonMarker, TopoJson, @@ -77,6 +78,7 @@ 'FitBounds', 'GeoJson', 'GeoJsonTooltip', + 'GeoJsonStyleMap', 'Html', 'IFrame', 'Icon', diff --git a/folium/features.py b/folium/features.py index 37c9ccc0e5..861a1282e4 100644 --- a/folium/features.py +++ b/folium/features.py @@ -421,7 +421,7 @@ class GeoJson(Layer): } {% endif %} ).addTo({{this._parent.get_name()}}); - {{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;}); + {% if not this.style_map %}{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});{% endif %} {% endmacro %} """) # noqa @@ -451,15 +451,20 @@ def __init__(self, data, style_function=None, name=None, else: raise ValueError('Unhandled object {!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, GeoJsonStyleMap): + self.add_child(style_function) + self.style_map = True + else: + self.style_map = False + self.style_function = style_function or (lambda x: {}) + self._validate_function(self.style_function, 'style_function') + self._validate_function(self.highlight_function, 'highlight_function') if isinstance(tooltip, (GeoJsonTooltip, Tooltip)): @@ -491,10 +496,12 @@ 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.setdefault('properties', {}).setdefault('style', {}).update(self.style_function(feature)) # noqa - feature.setdefault('properties', {}).setdefault('highlight', {}).update( - self.highlight_function(feature)) # noqa + if not self.style_map: + for feature in self.data['features']: + feature.setdefault('properties', {}).setdefault('style', {}).update(self.style_function(feature)) # noqa + feature.setdefault('properties', {}).setdefault('highlight', {}).update( + self.highlight_function(feature)) # noqa + return json.dumps(self.data, sort_keys=True) def _get_self_bounds(self): @@ -609,7 +616,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:]) @@ -797,6 +803,27 @@ def render(self, **kwargs): super(GeoJsonTooltip, self).render(**kwargs) +class GeoJsonStyleMap(MacroElement): + _template = Template(u""" + {% macro script(this, kwargs) %} + {{ this._parent.get_name() }}.setStyle(function(feature) { + var val = {% if this.property_name is not none %}feature.properties.{{this.property_name}}{% else %}feature['id']{% endif %}; + {% for key in this.style_map %} + if (val == {{key}}) { return {{this.style_map[key]}}; } + {% endfor %} + return {{this.default}}; + }); + {% endmacro %} + """) # noqa + + def __init__(self, style_map, property_name=None, default=None): + 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. From 49f28265e39dcb87107f14a17407242a4237e190 Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Fri, 28 Dec 2018 17:10:23 +0100 Subject: [PATCH 2/9] Add GeoJsonStyleMap example to notebook --- examples/GeoJSON_and_choropleth.ipynb | 229 +++++++++++++++++--------- 1 file changed, 152 insertions(+), 77 deletions(-) diff --git a/examples/GeoJSON_and_choropleth.ipynb b/examples/GeoJSON_and_choropleth.ipynb index 7bdc1f695c..d5e7fcb1f7 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+13.gf509031.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, @@ -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,64 @@ "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", + " feature['properties'].pop('style', None)\n", + " \n", + "style_map = folium.GeoJsonStyleMap({\n", + " True: {\n", + " 'fillColor': 'green',\n", + " 'color': 'black',\n", + " 'weight': 2,\n", + " 'dashArray': '5, 5'\n", + " }}, property_name='has_e', 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 +361,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 9, "metadata": { "scrolled": true }, @@ -313,6 +370,19 @@ "data": { "text/html": [ "
\n", + "\n", "\n", " \n", " \n", @@ -360,7 +430,7 @@ "4 CA 10.1" ] }, - "execution_count": 8, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } @@ -384,7 +454,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 10, "metadata": {}, "outputs": [ { @@ -400,10 +470,10 @@ "3.210.3" ], "text/plain": [ - "" + "" ] }, - "execution_count": 9, + "execution_count": 10, "metadata": {}, "output_type": "execute_result" } @@ -429,16 +499,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 +528,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 +562,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 +576,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 +585,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 +616,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 +637,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 +658,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 +676,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 +703,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 +717,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 +739,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 +753,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 +782,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 +796,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 +826,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 +840,7 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 20, "metadata": { "scrolled": false }, @@ -773,13 +848,13 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 19, + "execution_count": 20, "metadata": {}, "output_type": "execute_result" } @@ -800,7 +875,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 +889,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 21, "metadata": { "scrolled": false }, @@ -822,13 +897,13 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 20, + "execution_count": 21, "metadata": {}, "output_type": "execute_result" } @@ -850,7 +925,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 +939,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 22, "metadata": {}, "outputs": [ { @@ -878,13 +953,13 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 21, + "execution_count": 22, "metadata": {}, "output_type": "execute_result" } @@ -908,7 +983,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 +1005,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.1" + "version": "3.6.7" }, "toc": { "base_numbering": 1, From 4a7559feb9305f5aa3bfc00b7f19769f1242ab41 Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Fri, 28 Dec 2018 17:13:28 +0100 Subject: [PATCH 3/9] Resolve wrong import ordering --- folium/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/folium/__init__.py b/folium/__init__.py index 64cd39ad9c..19b2c0f4d8 100644 --- a/folium/__init__.py +++ b/folium/__init__.py @@ -27,8 +27,8 @@ CustomIcon, DivIcon, GeoJson, - GeoJsonTooltip, GeoJsonStyleMap, + GeoJsonTooltip, LatLngPopup, RegularPolygonMarker, TopoJson, @@ -77,8 +77,8 @@ 'Figure', 'FitBounds', 'GeoJson', - 'GeoJsonTooltip', 'GeoJsonStyleMap', + 'GeoJsonTooltip', 'Html', 'IFrame', 'Icon', From fb1cf291c63fb08fe089a0d0d7b148483907211c Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Sun, 30 Dec 2018 16:44:15 +0100 Subject: [PATCH 4/9] Inherit style from the default --- folium/features.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/folium/features.py b/folium/features.py index 861a1282e4..921ff05c76 100644 --- a/folium/features.py +++ b/folium/features.py @@ -807,11 +807,12 @@ class GeoJsonStyleMap(MacroElement): _template = Template(u""" {% macro script(this, kwargs) %} {{ this._parent.get_name() }}.setStyle(function(feature) { + var style = {{this.default}} var val = {% if this.property_name is not none %}feature.properties.{{this.property_name}}{% else %}feature['id']{% endif %}; {% for key in this.style_map %} - if (val == {{key}}) { return {{this.style_map[key]}}; } + if (val == {{key}}) { return Object.assign(style, {{this.style_map[key]}}); } {% endfor %} - return {{this.default}}; + return style; }); {% endmacro %} """) # noqa From c67b707dfb1270ffd9aafb3dc65f883204e2db27 Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Sun, 30 Dec 2018 16:48:58 +0100 Subject: [PATCH 5/9] Require property to discourage using separate style for each feature --- examples/GeoJSON_and_choropleth.ipynb | 82 +++++++++++++-------------- folium/features.py | 4 +- 2 files changed, 43 insertions(+), 43 deletions(-) diff --git a/examples/GeoJSON_and_choropleth.ipynb b/examples/GeoJSON_and_choropleth.ipynb index d5e7fcb1f7..f0ba690396 100644 --- a/examples/GeoJSON_and_choropleth.ipynb +++ b/examples/GeoJSON_and_choropleth.ipynb @@ -9,7 +9,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "0.7.0+13.gf509031.dirty\n" + "0.7.0+18.g7028e2d.dirty\n" ] } ], @@ -96,10 +96,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 3, @@ -132,10 +132,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 4, @@ -168,10 +168,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 5, @@ -217,10 +217,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 6, @@ -261,10 +261,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 7, @@ -307,10 +307,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 8, @@ -325,13 +325,13 @@ " feature['properties']['has_e'] = 'e' in feature['properties']['name'].lower()\n", " feature['properties'].pop('style', None)\n", " \n", - "style_map = folium.GeoJsonStyleMap({\n", - " True: {\n", - " 'fillColor': 'green',\n", - " 'color': 'black',\n", - " 'weight': 2,\n", - " 'dashArray': '5, 5'\n", - " }}, property_name='has_e', default={\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", @@ -470,7 +470,7 @@ "3.210.3" ], "text/plain": [ - "" + "" ] }, "execution_count": 10, @@ -534,10 +534,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 12, @@ -591,10 +591,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 14, @@ -643,10 +643,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 15, @@ -682,10 +682,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 16, @@ -723,10 +723,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 17, @@ -759,10 +759,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 18, @@ -802,10 +802,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 19, @@ -848,10 +848,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 20, @@ -897,10 +897,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 21, @@ -953,10 +953,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 22, diff --git a/folium/features.py b/folium/features.py index 921ff05c76..60867a928b 100644 --- a/folium/features.py +++ b/folium/features.py @@ -808,7 +808,7 @@ class GeoJsonStyleMap(MacroElement): {% macro script(this, kwargs) %} {{ this._parent.get_name() }}.setStyle(function(feature) { var style = {{this.default}} - var val = {% if this.property_name is not none %}feature.properties.{{this.property_name}}{% else %}feature['id']{% endif %}; + 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 %} @@ -817,7 +817,7 @@ class GeoJsonStyleMap(MacroElement): {% endmacro %} """) # noqa - def __init__(self, style_map, property_name=None, default=None): + def __init__(self, property_name, style_map, default=None): super(GeoJsonStyleMap, self).__init__() self._name = "GeoJsonStyleMap" self.property_name = property_name From 7a3c982241a8c45c78f7cb770d18280c801e5c35 Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Sun, 30 Dec 2018 18:27:46 +0100 Subject: [PATCH 6/9] Create GeoJsonStyleFunction base and subclass for passed in callable --- examples/GeoJSON_and_choropleth.ipynb | 71 +++++++++++++-------------- folium/features.py | 49 ++++++++++++------ 2 files changed, 70 insertions(+), 50 deletions(-) diff --git a/examples/GeoJSON_and_choropleth.ipynb b/examples/GeoJSON_and_choropleth.ipynb index f0ba690396..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.7.0+18.g7028e2d.dirty\n" + "0.7.0+19.g7a1fe3c.dirty\n" ] } ], @@ -96,10 +96,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 3, @@ -132,10 +132,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 4, @@ -168,10 +168,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 5, @@ -190,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" ] @@ -217,10 +217,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 6, @@ -261,10 +261,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 7, @@ -307,10 +307,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 8, @@ -323,7 +323,6 @@ "\n", "for feature in geo_json_data['features']:\n", " feature['properties']['has_e'] = 'e' in feature['properties']['name'].lower()\n", - " feature['properties'].pop('style', None)\n", " \n", "style_map = folium.GeoJsonStyleMap(\n", " property_name='has_e',\n", @@ -470,7 +469,7 @@ "3.210.3" ], "text/plain": [ - "" + "" ] }, "execution_count": 10, @@ -534,10 +533,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 12, @@ -591,10 +590,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 14, @@ -643,10 +642,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 15, @@ -682,10 +681,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 16, @@ -723,10 +722,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 17, @@ -759,10 +758,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 18, @@ -802,10 +801,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 19, @@ -848,10 +847,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 20, @@ -897,10 +896,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 21, @@ -953,10 +952,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 22, diff --git a/folium/features.py b/folium/features.py index 60867a928b..7c61cd0661 100644 --- a/folium/features.py +++ b/folium/features.py @@ -421,7 +421,6 @@ class GeoJson(Layer): } {% endif %} ).addTo({{this._parent.get_name()}}); - {% if not this.style_map %}{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});{% endif %} {% endmacro %} """) # noqa @@ -457,13 +456,14 @@ def __init__(self, data, style_function=None, name=None, self.smooth_factor = smooth_factor - if isinstance(style_function, GeoJsonStyleMap): + if isinstance(style_function, GeoJsonStyleFunction): self.add_child(style_function) - self.style_map = True + self.should_style_data = False else: - self.style_map = False 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') @@ -496,7 +496,7 @@ def style_data(self): self.data = {'type': 'Feature', 'geometry': self.data} self.data = {'type': 'FeatureCollection', 'features': [self.data]} - if not self.style_map: + if self.should_style_data: for feature in self.data['features']: feature.setdefault('properties', {}).setdefault('style', {}).update(self.style_function(feature)) # noqa feature.setdefault('properties', {}).setdefault('highlight', {}).update( @@ -803,20 +803,41 @@ def render(self, **kwargs): super(GeoJsonTooltip, self).render(**kwargs) -class GeoJsonStyleMap(MacroElement): +class GeoJsonStyleFunction(MacroElement): _template = Template(u""" {% macro script(this, kwargs) %} - {{ this._parent.get_name() }}.setStyle(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; - }); + {{ 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): + 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): super(GeoJsonStyleMap, self).__init__() self._name = "GeoJsonStyleMap" From 4612a73274bab49af7a0b36b6dae26a5ef5e10c4 Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Fri, 4 Jan 2019 14:25:34 +0000 Subject: [PATCH 7/9] Add documentation around GeoJsonStyleFunction --- folium/features.py | 61 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/folium/features.py b/folium/features.py index 7c61cd0661..e1c6fa8c8a 100644 --- a/folium/features.py +++ b/folium/features.py @@ -352,7 +352,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. @@ -804,6 +804,17 @@ def render(self, **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) }}); @@ -820,6 +831,35 @@ class GeoJsonStylePropertyFunction(GeoJsonStyleFunction): """) # 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 @@ -839,6 +879,25 @@ class GeoJsonStyleMap(GeoJsonStyleFunction): """) # 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 From 30e8b528a6e712f03856ef25c6a0db252c98b56b Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Fri, 4 Jan 2019 15:50:47 +0000 Subject: [PATCH 8/9] Make GeoJsonStyleMap importable from package root --- folium/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/folium/__init__.py b/folium/__init__.py index 19b2c0f4d8..1636940a11 100644 --- a/folium/__init__.py +++ b/folium/__init__.py @@ -28,6 +28,7 @@ DivIcon, GeoJson, GeoJsonStyleMap, + GeoJsonStylePropertyFunction, GeoJsonTooltip, LatLngPopup, RegularPolygonMarker, @@ -78,6 +79,7 @@ 'FitBounds', 'GeoJson', 'GeoJsonStyleMap', + 'GeoJsonStylePropertyFunction', 'GeoJsonTooltip', 'Html', 'IFrame', From 9b5a9ac035648dac2df95d9023c676ba5d072537 Mon Sep 17 00:00:00 2001 From: Sander van Dijk Date: Fri, 4 Jan 2019 15:51:25 +0000 Subject: [PATCH 9/9] Add basic tests for GeoJsonStylePropertyFunction, GeoJsonStyleMap --- tests/test_features.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) 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_()