diff --git a/.gitignore b/.gitignore index 64f67788a4..173e59bc1b 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ latest_logs/ folium/_version.py .vscode/ venv/ +.venv diff --git a/examples/plugin-GroupedLayerControl.ipynb b/examples/plugin-GroupedLayerControl.ipynb new file mode 100644 index 0000000000..05c2d6dc9e --- /dev/null +++ b/examples/plugin-GroupedLayerControl.ipynb @@ -0,0 +1,403 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# GroupedLayerControl\n", + "\n", + "We can create a GroupedLayerControl and define what layers we want to group together. Those layers won't show up in the regular layer control.\n", + "\n", + "`GroupedLayerControl` takes the same arguments as `LayerControl`.\n", + "\n", + "By default groups are exclusive, meaning only one layer in a group can be active at a time." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
Make this Notebook Trusted to load map: File -> Trust Notebook
" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import folium\n", + "from folium.plugins import GroupedLayerControl\n", + "\n", + "m = folium.Map([40., 70.], zoom_start=6)\n", + "\n", + "fg1 = folium.FeatureGroup(name='g1')\n", + "fg2 = folium.FeatureGroup(name='g2')\n", + "fg3 = folium.FeatureGroup(name='g3')\n", + "folium.Marker([40, 74]).add_to(fg1)\n", + "folium.Marker([38, 72]).add_to(fg2)\n", + "folium.Marker([40, 72]).add_to(fg3)\n", + "m.add_child(fg1)\n", + "m.add_child(fg2)\n", + "m.add_child(fg3)\n", + "\n", + "folium.LayerControl(collapsed=False).add_to(m)\n", + "\n", + "GroupedLayerControl(\n", + " groups={'groups1': [fg1, fg2]},\n", + " collapsed=False,\n", + ").add_to(m)\n", + "\n", + "m" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's also possible to have check boxes instead of radio buttons, so multiple layers within a group can be active.\n", + "\n", + "In this example the layers are not shown by default, but can all be activated." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
Make this Notebook Trusted to load map: File -> Trust Notebook
" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "m = folium.Map([40., 70.], zoom_start=6)\n", + "\n", + "fg1 = folium.FeatureGroup(name='g1', show=False)\n", + "fg2 = folium.FeatureGroup(name='g2', show=False)\n", + "fg3 = folium.FeatureGroup(name='g3')\n", + "folium.Marker([40, 74]).add_to(fg1)\n", + "folium.Marker([38, 72]).add_to(fg2)\n", + "folium.Marker([40, 72]).add_to(fg3)\n", + "m.add_child(fg1)\n", + "m.add_child(fg2)\n", + "m.add_child(fg3)\n", + "\n", + "folium.LayerControl(collapsed=False).add_to(m)\n", + "\n", + "GroupedLayerControl(\n", + " groups={'groups1': [fg1, fg2]},\n", + " exclusive_groups=False,\n", + " collapsed=False,\n", + ").add_to(m)\n", + "\n", + "m" + ] + } + ], + "metadata": { + "interpreter": { + "hash": "fe5dd214bcd3c7acb291c354b42a251cd956bb0540c24510fdecda31bd920a27" + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.13" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/folium/plugins/__init__.py b/folium/plugins/__init__.py index 048c3a3350..3dea16c9d3 100644 --- a/folium/plugins/__init__.py +++ b/folium/plugins/__init__.py @@ -16,6 +16,7 @@ from folium.plugins.float_image import FloatImage from folium.plugins.fullscreen import Fullscreen from folium.plugins.geocoder import Geocoder +from folium.plugins.groupedlayercontrol import GroupedLayerControl from folium.plugins.heat_map import HeatMap from folium.plugins.heat_map_withtime import HeatMapWithTime from folium.plugins.locate_control import LocateControl @@ -49,6 +50,7 @@ 'FloatImage', 'Fullscreen', 'Geocoder', + 'GroupedLayerControl', 'HeatMap', 'HeatMapWithTime', 'LocateControl', diff --git a/folium/plugins/groupedlayercontrol.py b/folium/plugins/groupedlayercontrol.py new file mode 100644 index 0000000000..bd66f76014 --- /dev/null +++ b/folium/plugins/groupedlayercontrol.py @@ -0,0 +1,87 @@ +from branca.element import MacroElement +from folium.elements import JSCSSMixin +from folium.utilities import parse_options + +from jinja2 import Template + + +class GroupedLayerControl(JSCSSMixin, MacroElement): + """ + Create a Layer Control with groups of overlays. + + Parameters + ---------- + groups : dict + A dictionary where the keys are group names and the values are lists + of layer objects. + e.g. { + "Group 1": [layer1, layer2], + "Group 2": [layer3, layer4] + } + exclusive_groups: bool, default True + Whether to use radio buttons (default) or checkboxes. + If you want to use both, use two separate instances of this class. + **kwargs + Additional (possibly inherited) options. See + https://leafletjs.com/reference.html#control-layers + + """ + default_js = [ + ('leaflet.groupedlayercontrol.min.js', + 'https://cdnjs.cloudflare.com/ajax/libs/leaflet-groupedlayercontrol/0.6.1/leaflet.groupedlayercontrol.min.js'), + ] + default_css = [ + ('leaflet.groupedlayercontrol.min.css', + 'https://cdnjs.cloudflare.com/ajax/libs/leaflet-groupedlayercontrol/0.6.1/leaflet.groupedlayercontrol.min.css') + ] + + _template = Template(""" + {% macro script(this,kwargs) %} + + L.control.groupedLayers( + null, + { + {%- for group_name, overlays in this.grouped_overlays.items() %} + {{ group_name|tojson }} : { + {%- for overlaykey, val in overlays.items() %} + {{ overlaykey|tojson }} : {{val}}, + {%- endfor %} + }, + {%- endfor %} + }, + {{ this.options|tojson }}, + ).addTo({{this._parent.get_name()}}); + + {%- for val in this.layers_untoggle %} + {{ val }}.remove(); + {%- endfor %} + + {% endmacro %} + """) + + def __init__( + self, + groups, + exclusive_groups=True, + **kwargs + ): + super().__init__() + self._name = 'GroupedLayerControl' + self.options = parse_options(**kwargs) + if exclusive_groups: + self.options['exclusiveGroups'] = list(groups.keys()) + self.layers_untoggle = set() + self.grouped_overlays = {} + for group_name, sublist in groups.items(): + self.grouped_overlays[group_name] = {} + for element in sublist: + self.grouped_overlays[group_name][element.layer_name] = element.get_name() + if not element.show: + self.layers_untoggle.add(element.get_name()) + # make sure the elements used in GroupedLayerControl + # don't show up in the regular LayerControl. + element.control = False + if exclusive_groups: + # only enable the first radio button + for element in sublist[1:]: + self.layers_untoggle.add(element.get_name()) diff --git a/tests/plugins/test_grouped_layer_control.py b/tests/plugins/test_grouped_layer_control.py new file mode 100644 index 0000000000..68d66ff4bc --- /dev/null +++ b/tests/plugins/test_grouped_layer_control.py @@ -0,0 +1,35 @@ +import folium +from folium.plugins import groupedlayercontrol +from folium.utilities import normalize + + +def test_feature_group_sub_group(): + m = folium.Map([40., 70.], zoom_start=6) + fg1 = folium.FeatureGroup(name='g1') + fg2 = folium.FeatureGroup(name='g2') + fg3 = folium.FeatureGroup(name='g3') + folium.Marker([40, 74]).add_to(fg1) + folium.Marker([38, 72]).add_to(fg2) + folium.Marker([40, 72]).add_to(fg3) + m.add_child(fg1) + m.add_child(fg2) + m.add_child(fg3) + lc = groupedlayercontrol.GroupedLayerControl(groups={'groups1': [fg1, fg2]}) + lc.add_to(m) + out = normalize(m._parent.render()) + + assert 'https://cdnjs.cloudflare.com/ajax/libs/leaflet-groupedlayercontrol/0.6.1/leaflet.groupedlayercontrol.min.js' in out # noqa + + assert normalize(f""" + L.control.groupedLayers( + null, + {{ + "groups1" : {{ + "g1" : {fg1.get_name()}, + "g2" : {fg2.get_name()}, + }}, + }}, + {{"exclusiveGroups": ["groups1"]}}, + ).addTo({m.get_name()}); + {fg2.get_name()}.remove(); + """) in out