diff --git a/examples/GeoJsonPopupAndTooltip.ipynb b/examples/GeoJsonPopupAndTooltip.ipynb new file mode 100644 index 0000000000..fd8ca90b87 --- /dev/null +++ b/examples/GeoJsonPopupAndTooltip.ipynb @@ -0,0 +1,279 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import geopandas as gpd\n", + "import pandas as pd\n", + "import folium, branca\n", + "import fiona, requests, json\n", + "\n", + "from folium.features import GeoJson, GeoJsonTooltip, GeoJsonPopup" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": "0.8.2+132.gc3eb242\n" + } + ], + "source": [ + "print(folium.__version__)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "income = pd.read_csv(r\"https://raw.githubusercontent.com/pri-data/50-states/master/data/income-counties-states-national.csv\", dtype={\"fips\":str})\n", + "income['income-2015']=pd.to_numeric(income['income-2015'], errors='coerce')" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": "
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
fipscountystateincome-2015income-1989aincome-1989bchange
000000USUS55775.02890653367.281024.316843
101000AlabamaAL44833.02220240990.118778.571546
201001Autauga CountyAL56580.02689849660.0403012.230399
301003Baldwin CountyAL52387.02404344389.0381815.267074
401005Barbour CountyAL31433.01867334474.75398-9.676945
\n
", + "text/plain": " fips county state income-2015 income-1989a income-1989b \\\n0 00000 US US 55775.0 28906 53367.28102 \n1 01000 Alabama AL 44833.0 22202 40990.11877 \n2 01001 Autauga County AL 56580.0 26898 49660.04030 \n3 01003 Baldwin County AL 52387.0 24043 44389.03818 \n4 01005 Barbour County AL 31433.0 18673 34474.75398 \n\n change \n0 4.316843 \n1 8.571546 \n2 12.230399 \n3 15.267074 \n4 -9.676945 " + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "income.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": "
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
geometryname
0POLYGON ((-87.35930 35.00118, -85.60667 34.984...Alabama
1MULTIPOLYGON (((-131.60202 55.11798, -131.5691...Alaska
2POLYGON ((-109.04250 37.00026, -109.04798 31.3...Arizona
3POLYGON ((-94.47384 36.50186, -90.15254 36.496...Arkansas
4POLYGON ((-123.23326 42.00619, -122.37885 42.0...California
\n
", + "text/plain": " geometry name\n0 POLYGON ((-87.35930 35.00118, -85.60667 34.984... Alabama\n1 MULTIPOLYGON (((-131.60202 55.11798, -131.5691... Alaska\n2 POLYGON ((-109.04250 37.00026, -109.04798 31.3... Arizona\n3 POLYGON ((-94.47384 36.50186, -90.15254 36.496... Arkansas\n4 POLYGON ((-123.23326 42.00619, -122.37885 42.0... California" + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "states = gpd.GeoDataFrame.from_features(requests.get(r\"https://raw.githubusercontent.com/python-visualization/folium/master/examples/data/us-states.json\").json(), crs=fiona.crs.from_epsg(4326))\n", + "\n", + "states.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": "
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
namealpha-2
0AlabamaAL
1AlaskaAK
2ArizonaAZ
\n
", + "text/plain": " name alpha-2\n0 Alabama AL\n1 Alaska AK\n2 Arizona AZ" + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "abbrs = pd.read_json(json.dumps(requests.get('https://gist.githubusercontent.com/tvpmb/4734703/raw/b54d03154c339ed3047c66fefcece4727dfc931a/US%2520State%2520List').json()))\n", + "\n", + "abbrs.head(3)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": "
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
geometrynamealpha-2
0POLYGON ((-87.35930 35.00118, -85.60667 34.984...AlabamaAL
1MULTIPOLYGON (((-131.60202 55.11798, -131.5691...AlaskaAK
2POLYGON ((-109.04250 37.00026, -109.04798 31.3...ArizonaAZ
3POLYGON ((-94.47384 36.50186, -90.15254 36.496...ArkansasAR
4POLYGON ((-123.23326 42.00619, -120.00186 41.9...CaliforniaCA
\n
", + "text/plain": " geometry name alpha-2\n0 POLYGON ((-87.35930 35.00118, -85.60667 34.984... Alabama AL\n1 MULTIPOLYGON (((-131.60202 55.11798, -131.5691... Alaska AK\n2 POLYGON ((-109.04250 37.00026, -109.04798 31.3... Arizona AZ\n3 POLYGON ((-94.47384 36.50186, -90.15254 36.496... Arkansas AR\n4 POLYGON ((-123.23326 42.00619, -120.00186 41.9... California CA" + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "statesmerge = states.merge(abbrs,how='left', left_on='name', right_on='name')\n", + "statesmerge['geometry']=statesmerge.geometry.simplify(.05)\n", + "\n", + "statesmerge.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": "
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
income-2015
state
AK62561.5
AL38721.5
AR37890.0
AZ43810.0
CA53341.0
\n
", + "text/plain": " income-2015\nstate \nAK 62561.5\nAL 38721.5\nAR 37890.0\nAZ 43810.0\nCA 53341.0" + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "income.groupby(by=\"state\")[['state','income-2015']].median().head()" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "statesmerge['medianincome']=statesmerge.merge(income.groupby(by=\"state\")[['state','income-2015']].median(), how='left', left_on='alpha-2', right_on='state')['income-2015']\n", + "statesmerge['change']=statesmerge.merge(income.groupby(by=\"state\")[['state','change']].median(), how='left', left_on='alpha-2', right_on='state')['change']" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": "
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
geometrynamealpha-2medianincomechange
0POLYGON ((-87.35930 35.00118, -85.60667 34.984...AlabamaAL38721.52.779114
1MULTIPOLYGON (((-131.60202 55.11798, -131.5691...AlaskaAK62561.514.758367
2POLYGON ((-109.04250 37.00026, -109.04798 31.3...ArizonaAZ43810.0NaN
3POLYGON ((-94.47384 36.50186, -90.15254 36.496...ArkansasAR37890.010.897394
4POLYGON ((-123.23326 42.00619, -120.00186 41.9...CaliforniaCA53341.06.716596
\n
", + "text/plain": " geometry name alpha-2 \\\n0 POLYGON ((-87.35930 35.00118, -85.60667 34.984... Alabama AL \n1 MULTIPOLYGON (((-131.60202 55.11798, -131.5691... Alaska AK \n2 POLYGON ((-109.04250 37.00026, -109.04798 31.3... Arizona AZ \n3 POLYGON ((-94.47384 36.50186, -90.15254 36.496... Arkansas AR \n4 POLYGON ((-123.23326 42.00619, -120.00186 41.9... California CA \n\n medianincome change \n0 38721.5 2.779114 \n1 62561.5 14.758367 \n2 43810.0 NaN \n3 37890.0 10.897394 \n4 53341.0 6.716596 " + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "statesmerge.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": "43969.375" + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "statesmerge['medianincome'].quantile(0.25)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "colormap = branca.colormap.LinearColormap(vmin=statesmerge['change'].quantile(0.0), \n", + " vmax=statesmerge['change'].quantile(1), \n", + " colors=['red','orange','lightblue','green','darkgreen'],\n", + " caption=\"State Level Median County Household Income (%)\")" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": "
", + "text/plain": "" + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "m = folium.Map(location=[35.3, -97.6], zoom_start=4)\n", + "\n", + "popup=GeoJsonPopup(fields=['name','change'], aliases=['State',\"% Change\"], localize=True, labels=True, style=\"background-color: yellow;\")\n", + "\n", + "tooltip=GeoJsonTooltip(\n", + " fields=[\"name\", \"medianincome\", \"change\"],\n", + " aliases=[\"State:\", \"2015 Median Income(USD):\", \"Median % Change:\"],\n", + " localize=True,\n", + " sticky=False,\n", + " labels=True,\n", + " style=\"\"\"\n", + " background-color: #F0EFEF;\n", + " border: 2px solid black;\n", + " border-radius: 3px;\n", + " box-shadow: 3px;\n", + " \"\"\",\n", + " max_width=800,\n", + ")\n", + "\n", + "\n", + "g = folium.GeoJson(\n", + " statesmerge,\n", + " style_function=lambda x: {\n", + " \"fillColor\": colormap(x[\"properties\"][\"change\"])\n", + " if x[\"properties\"][\"change\"] is not None\n", + " else \"transparent\",\n", + " \"color\": \"black\",\n", + " \"fillOpacity\": 0.4,\n", + " },\n", + " tooltip=tooltip,\n", + " popup=popup\n", + ").add_to(m)\n", + "\n", + "colormap.add_to(m)\n", + "\n", + "m" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "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.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/folium/__init__.py b/folium/__init__.py index 39398431dc..c55669af41 100644 --- a/folium/__init__.py +++ b/folium/__init__.py @@ -25,6 +25,7 @@ DivIcon, GeoJson, GeoJsonTooltip, + GeoJsonPopup, LatLngPopup, RegularPolygonMarker, TopoJson, diff --git a/folium/features.py b/folium/features.py index b4ef5d34a4..e96d171be2 100644 --- a/folium/features.py +++ b/folium/features.py @@ -25,6 +25,7 @@ none_min, get_obj_in_upper_tree, parse_options, + camelize ) from folium.vector_layers import PolyLine, path_options @@ -437,7 +438,7 @@ class GeoJson(Layer): def __init__(self, data, style_function=None, highlight_function=None, # noqa name=None, overlay=True, control=True, show=True, - smooth_factor=None, tooltip=None, embed=True): + smooth_factor=None, tooltip=None, embed=True, popup=None): super(GeoJson, self).__init__(name=name, overlay=overlay, control=control, show=show) self._name = 'GeoJson' @@ -467,6 +468,8 @@ def __init__(self, data, style_function=None, highlight_function=None, # noqa self.add_child(tooltip) elif tooltip is not None: self.add_child(Tooltip(tooltip)) + if isinstance(popup, (GeoJsonPopup)): + self.add_child(popup) def process_data(self, data): """Convert an unknown data input into a geojson dictionary.""" @@ -796,7 +799,112 @@ def get_bounds(self): ] -class GeoJsonTooltip(Tooltip): +class GeoJsonDetail(MacroElement): + + """ + Base class for GeoJsonTooltip and GeoJsonPopup to inherit methods and + template structure from. Not for direct usage. + + """ + base_template = u""" + function(layer){ + let div = L.DomUtil.create('div'); + {% if this.fields %} + let handleObject = feature=>typeof(feature)=='object' ? JSON.stringify(feature) : feature; + let fields = {{ this.fields | tojson | safe }}; + let aliases = {{ this.aliases | tojson | safe }}; + let table = '' + + String( + fields.map( + (v,i)=> + `{% if this.labels %} + + {% endif %} + + `).join('')) + +'
${aliases[i]{% if this.localize %}.toLocaleString(){% endif %}}${handleObject(layer.feature.properties[v]){% if this.localize %}.toLocaleString(){% endif %}}
'; + div.innerHTML=table; + {% endif %} + return div + } + """ + + def __init__(self, fields, aliases=None, labels=True, localize=False, style=None, + class_name="geojsondetail"): + super(GeoJsonDetail, self).__init__() + assert isinstance(fields, (list, tuple)), 'Please pass a list or ' \ + 'tuple to fields.' + if aliases is not None: + assert isinstance(aliases, (list, tuple)) + assert len(fields) == len(aliases), 'fields and aliases must have' \ + ' the same length.' + assert isinstance(labels, bool), 'labels requires a boolean value.' + assert isinstance(localize, bool), 'localize must be bool.' + self._name = "GeoJsonDetail" + self.fields = fields + self.aliases = aliases if aliases is not None else fields + self.labels = labels + self.localize = localize + self.class_name = class_name + if style: + assert isinstance(style, str), \ + 'Pass a valid inline HTML style property string to style.' + # noqa outside of type checking. + self.style = style + + def warn_for_geometry_collections(self): + """Checks for GeoJson GeometryCollection features to warn user about incompatibility.""" + geom_collections = [ + feature.get('properties') if feature.get('properties') is not None else key + for key, feature in enumerate(self._parent.data['features']) + if feature['geometry']['type'] == 'GeometryCollection' + ] + if any(geom_collections): + warnings.warn( + "{} is not configured to render for GeoJson GeometryCollection geometries. " + "Please consider reworking these features: {} to MultiPolygon for full functionality.\n" + "https://tools.ietf.org/html/rfc7946#page-9".format(self._name, geom_collections), UserWarning) + + def render(self, **kwargs): + """Renders the HTML representation of the element.""" + figure = self.get_root() + if isinstance(self._parent, GeoJson): + keys = tuple(self._parent.data['features'][0]['properties'].keys()) + self.warn_for_geometry_collections() + elif isinstance(self._parent, TopoJson): + obj_name = self._parent.object_path.split('.')[-1] + keys = tuple(self._parent.data['objects'][obj_name][ + 'geometries'][0]['properties'].keys()) + else: + raise TypeError('You cannot add a {} to anything other than a ' + 'GeoJson or TopoJson object.'.format(self._name)) + keys = tuple(x for x in keys if x not in ('style', 'highlight')) + for value in self.fields: + assert value in keys, ('The field {} is not available in the data. ' + 'Choose from: {}.'.format(value, keys)) + figure.header.add_child(Element( + Template(u""" + + """).render(this=self)), name=self.get_name() + "tablestyle" + ) + + super(GeoJsonDetail, self).render() + + +class GeoJsonTooltip(GeoJsonDetail): """ Create a tooltip that uses data from either geojson or topojson. @@ -839,93 +947,76 @@ class GeoJsonTooltip(Tooltip): >>> GeoJsonTooltip(fields=('CNTY_NM',), labels=False, sticky=False) """ _template = Template(u""" - {% macro script(this, kwargs) %} - {{ this._parent.get_name() }}.bindTooltip( - function(layer){ - // Convert non-primitive to String. - let handleObject = (feature)=>typeof(feature)=='object' ? JSON.stringify(feature) : feature; - let fields = {{ this.fields|tojson }}; - {%- if this.aliases %} - let aliases = {{ this.aliases|tojson }}; - {%- endif %} - return '' + - String( - fields.map( - columnname=> - `{% if this.labels %} - {% if this.aliases %} - ${aliases[fields.indexOf(columnname)] - {% if this.localize %}.toLocaleString(){% endif %}} - {% else %} - ${ columnname{% if this.localize %}.toLocaleString(){% endif %}} - {% endif %} - {% endif %} - ${handleObject(layer.feature.properties[columnname]) - {% if this.localize %}.toLocaleString(){% endif %}}` - ).join('')) - +'' - }, {{ this.options|tojson }}); - {% endmacro %} - """) - - def __init__(self, fields, aliases=None, labels=True, - localize=False, style=None, sticky=True, **kwargs): + {% macro script(this, kwargs) %} + {{ this._parent.get_name() }}.bindTooltip(""" + GeoJsonDetail.base_template + + u""",{{ this.tooltip_options | tojson | safe }}); + {% endmacro %} + """) + + def __init__(self, fields, aliases=None, labels=True, localize=False, + style=None, class_name='foliumtooltip', sticky=True, **kwargs): super(GeoJsonTooltip, self).__init__( - text='', style=style, sticky=sticky, **kwargs + fields=fields, aliases=aliases, labels=labels, localize=localize, + style=style, class_name=class_name ) self._name = 'GeoJsonTooltip' + kwargs.update({'sticky': sticky, 'class_name': class_name}) + self.tooltip_options = { + camelize(key): kwargs[key] for key in kwargs.keys()} - assert isinstance(fields, (list, tuple)), 'Please pass a list or ' \ - 'tuple to fields.' - if aliases is not None: - assert isinstance(aliases, (list, tuple)) - assert len(fields) == len(aliases), 'fields and aliases must have' \ - ' the same length.' - assert isinstance(labels, bool), 'labels requires a boolean value.' - assert isinstance(localize, bool), 'localize must be bool.' - assert 'permanent' not in kwargs, 'The `permanent` option does not ' \ - 'work with GeoJsonTooltip.' - self.fields = fields - self.aliases = aliases - self.labels = labels - self.localize = localize - if style: - assert isinstance(style, str), \ - 'Pass a valid inline HTML style property string to style.' - # noqa outside of type checking. - self.style = style +class GeoJsonPopup(GeoJsonDetail): + """ + Create a popup feature to bind to each element of a GeoJson layer based on + its attributes. - def warn_for_geometry_collections(self): - """Checks for GeoJson GeometryCollection features to warn user about incompatibility.""" - geom_collections = [ - feature.get('properties') if feature.get('properties') is not None else key - for key, feature in enumerate(self._parent.data['features']) - if feature['geometry']['type'] == 'GeometryCollection' - ] - if any(geom_collections): - warnings.warn( - "GeoJsonTooltip is not configured to render tooltips for GeoJson GeometryCollection geometries. " - "Please consider reworking these features: {} to MultiPolygon for full functionality.\n" - "https://tools.ietf.org/html/rfc7946#page-9".format(geom_collections), UserWarning) + Parameters + ---------- + fields: list or tuple. + Labels of GeoJson/TopoJson 'properties' or GeoPandas GeoDataFrame + columns you'd like to display. + aliases: list/tuple of strings, same length/order as fields, default None. + Optional aliases you'd like to display in the tooltip as field name + instead of the keys of `fields`. + labels: bool, default True. + Set to False to disable displaying the field names or aliases. + localize: bool, default False. + This will use JavaScript's .toLocaleString() to format 'clean' values + as strings for the user's location; i.e. 1,000,000.00 comma separators, + float truncation, etc. + *Available for most of JavaScript's primitive types (any data you'll + serve into the template). + style: str, default None. + HTML inline style properties like font and colors. Will be applied to + a div with the text in it. - def render(self, **kwargs): - """Renders the HTML representation of the element.""" - if isinstance(self._parent, GeoJson): - keys = tuple(self._parent.data['features'][0]['properties'].keys()) - self.warn_for_geometry_collections() - elif isinstance(self._parent, TopoJson): - obj_name = self._parent.object_path.split('.')[-1] - keys = tuple(self._parent.data['objects'][obj_name][ - 'geometries'][0]['properties'].keys()) - else: - raise TypeError('You cannot add a GeoJsonTooltip to anything else ' - 'than a GeoJson or TopoJson object.') - keys = tuple(x for x in keys if x not in ('style', 'highlight')) - for value in self.fields: - assert value in keys, ('The field {} is not available in the data. ' - 'Choose from: {}.'.format(value, keys)) - super(GeoJsonTooltip, self).render(**kwargs) + Examples + --- + gjson = folium.GeoJson(gdf).add_to(m) + + folium.features.GeoJsonPopup(fields=['NAME'], + labels=False + ).add_to(gjson) + """ + + _template = Template(u""" + {% macro script(this, kwargs) %} + let name_getter = '{{this._parent.get_name()}}'; + {{ this._parent.get_name() }}.bindPopup(""" + GeoJsonDetail.base_template + + u""",{{ this.popup_options | tojson | safe }}); + {% endmacro %} + """) + + def __init__(self, fields=None, aliases=None, labels=True, + style="margin: auto;", class_name='foliumpopup', localize=True, + **kwargs): + super(GeoJsonPopup, self).__init__( + fields=fields, aliases=aliases, labels=labels, localize=localize, + class_name=class_name, style=style) + self._name = "GeoJsonPopup" + kwargs.update({'class_name': self.class_name}) + self.popup_options = { + camelize(key): value for key, value in kwargs.items()} class Choropleth(FeatureGroup):