From 136e71ef64a80b410adf99b7e6b89affb4d5ef56 Mon Sep 17 00:00:00 2001 From: Andy Challis Date: Tue, 17 Oct 2017 20:12:15 +0100 Subject: [PATCH 1/9] Added in GeoJsonCss class into features Included an example of usage in the ipynb and accompanying data --- examples/GeoJsonCSS.ipynb | 63 +++++++++++++++++ examples/data/vlad.json | 71 +++++++++++++++++++ folium/__init__.py | 3 +- folium/features.py | 143 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 279 insertions(+), 1 deletion(-) create mode 100644 examples/GeoJsonCSS.ipynb create mode 100644 examples/data/vlad.json diff --git a/examples/GeoJsonCSS.ipynb b/examples/GeoJsonCSS.ipynb new file mode 100644 index 0000000000..1c883ae22a --- /dev/null +++ b/examples/GeoJsonCSS.ipynb @@ -0,0 +1,63 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Implementing the Leaflet-GeoJsonCSS library" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import os\n", + "import folium\n", + "\n", + "m = folium.Map(location=[55.75258, 37.61489], zoom_start=14, tiles = 'cartodbpositron')\n", + "\n", + "data = os.path.join('data', 'vlad.json')\n", + "\n", + "folium.GeoJsonCss(data).add_to(m)\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.6.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/examples/data/vlad.json b/examples/data/vlad.json new file mode 100644 index 0000000000..30576fd127 --- /dev/null +++ b/examples/data/vlad.json @@ -0,0 +1,71 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": { + "title": "Kremlin" + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [37.61489152908325,55.752586015356876], + [37.61577129364014,55.7539867694403], + [37.616543769836426,55.75506145183324], + [37.6177453994751,55.75443355110991], + [37.619526386260986,55.753491681072205], + [37.62143611907959,55.75252563689488], + [37.62117862701416,55.75211506087468], + [37.61875391006469,55.750762544596384], + [37.61813163757324,55.749989657097], + [37.61302471160889,55.749035602973365], + [37.612552642822266,55.74907183330299], + [37.6134967803955,55.750641781933986], + [37.61489152908325,55.752586015356876] + ]] + }, + "style": { + "color": "#CC0000", + "weight": 2, + "fill-opacity": 1, + "opacity": 1, + "dashArray": "3, 5" + }, + "popupTemplate": "{title}" + }, + { + "type": "Feature", + "properties": { + "title": "Vladimir's favourite road" + }, + "geometry": { + "type": "MultiLineString", + "coordinates": [[[37.611907,55.747355],[37.612639,55.747611],[37.613671,55.747839],[37.614446,55.748040],[37.616002,55.748446],[37.616364,55.748537],[37.616573,55.748585],[37.616779,55.748627],[37.617038,55.748677],[37.618375,55.748887],[37.620201,55.749173],[37.620494,55.749215],[37.620723,55.749246],[37.621209,55.749296],[37.622037,55.749388],[37.622402,55.749421],[37.622745,55.749461],[37.622990,55.749484],[37.623206,55.749507],[37.623680,55.749562],[37.624266,55.749640]],[[37.624245,55.749770],[37.623771,55.749678],[37.623476,55.749623],[37.623147,55.749577],[37.621484,55.749414],[37.620021,55.749222],[37.618740,55.749021],[37.617359,55.748819],[37.616927,55.748750],[37.616755,55.748721],[37.616592,55.748691],[37.616413,55.748652],[37.616225,55.748608],[37.614894,55.748251],[37.614139,55.748055],[37.613795,55.747971],[37.613487,55.747906],[37.612526,55.747741],[37.612248,55.747656],[37.611791,55.747497]]] + }, + "style": { + "color": "#CC0000", + "opacity": 1, + "weight": 4 + }, + "popupTemplate": "{title}" + }, + { + "type": "Feature", + "properties": { + "title": "Vladamir's house" + }, + "geometry": { + "type": "Point", + "coordinates": [37.61001, 55.752301] + }, + "style": { + "icon": { + "iconUrl": "http://downloadicons.net/sites/default/files/small-house-with-a-chimney-icon-70053.png", + "iconSize": [32, 32], + "iconAnchor": [16, 16] + } + }, + "popupTemplate": "{title}" + } + ] +} \ No newline at end of file diff --git a/folium/__init__.py b/folium/__init__.py index 2574ff8e48..38a7c39f60 100644 --- a/folium/__init__.py +++ b/folium/__init__.py @@ -9,7 +9,7 @@ from folium._version import get_versions from folium.features import ( - ClickForMarker, ColorLine, CustomIcon, DivIcon, GeoJson, + ClickForMarker, ColorLine, CustomIcon, DivIcon, GeoJson, GeoJsonCss, LatLngPopup, RegularPolygonMarker, TopoJson, Vega, VegaLite, ) @@ -52,6 +52,7 @@ 'CustomIcon', 'DivIcon', 'GeoJson', + 'GeoJsonCss', 'GeoJsonStyle', 'LatLngPopup', 'MarkerCluster', diff --git a/folium/features.py b/folium/features.py index de8899c6e5..0355559f5a 100644 --- a/folium/features.py +++ b/folium/features.py @@ -448,6 +448,149 @@ def _get_self_bounds(self): return get_bounds(self.data, lonlat=True) + +class GeoJsonCss(Layer): + """ + Creates a GeoJsonCss object for plotting into a Map. + + Parameters + ---------- + data: file, dict or str. + The GeoJSON data you want to plot. + * If file, then data will be read in the file and fully + embedded in Leaflet's JavaScript. + * 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. + highlight_function: function, default None + Function mapping a GeoJson Feature to a style dict for mouse events. + name : string, default None + The name of the Layer, as it will appear in LayerControls + overlay : bool, default False + Adds the layer as an optional overlay (True) or the base layer (False). + control : bool, default True + Whether the Layer will be included in LayerControls + smooth_factor: float, default None + How much to simplify the polyline on each zoom level. More means + better performance and smoother look, and less means more accurate + representation. Leaflet defaults to 1.0. + + Examples + -------- + >>> # Providing file that shall be embedded. + >>> GeoJsonCss(open('foo.json')) + >>> # Providing filename that shall not be embedded. + >>> GeoJsonCss('foo.json') + >>> # Providing dict. + >>> GeoJsonCss(json.load(open('foo.json'))) + >>> # Providing string. + >>> GeoJsonCss(open('foo.json').read()) + + >>> GeoJsonCss(geojson_with_css) + + """ + def __init__(self, data, name=None, + overlay=True, control=True, smooth_factor=None, + highlight_function=None, tooltip=None): + super(GeoJsonCss, self).__init__(name=name, overlay=overlay, + control=control) + self._name = 'GeoJsonCss' + self.tooltip = tooltip + if isinstance(data, dict): + self.embed = True + self.data = data + elif isinstance(data, text_type) or isinstance(data, binary_type): + self.embed = True + if data.lower().startswith(('http:', 'ftp:', 'https:')): + self.data = requests.get(data).json() + elif data.lstrip()[0] in '[{': # This is a GeoJSON inline string + self.data = json.loads(data) + else: # This is a filename + with open(data) as f: + self.data = json.loads(f.read()) + elif data.__class__.__name__ in ['GeoDataFrame', 'GeoSeries']: + self.embed = True + if hasattr(data, '__geo_interface__'): + # We have a GeoPandas 0.2 object. + self.data = json.loads(json.dumps(data.to_crs(epsg='4326').__geo_interface__)) # noqa + elif hasattr(data, 'columns'): + # We have a GeoDataFrame 0.1 + self.data = json.loads(data.to_crs(epsg='4326').to_json()) + else: + msg = 'Unable to transform this object to a GeoJSON.' + raise ValueError(msg) + else: + raise ValueError('Unhandled object {!r}.'.format(data)) + + self.highlight = highlight_function is not None + + if highlight_function is None: + def highlight_function(x): + return {} + + self.highlight_function = highlight_function + + self.smooth_factor = smooth_factor + + self._template = Template(u""" + {% macro script(this, kwargs) %} + + {% if this.highlight %} + {{this.get_name()}}_onEachFeature = function onEachFeature(feature, layer) { + layer.on({ + mouseout: function(e) { + e.target.setStyle(e.target.feature.properties.style);}, + mouseover: function(e) { + e.target.setStyle(e.target.feature.properties.highlight);}, + click: function(e) { + {{this._parent.get_name()}}.fitBounds(e.target.getBounds());} + }); + }; + {% endif %} + + var {{this.get_name()}} = L.geoJson.css( + {{this.data}} + {% if this.smooth_factor is not none or this.highlight %} + , { + {% if this.smooth_factor is not none %} + smoothFactor:{{this.smooth_factor}} + {% endif %} + + {% if this.highlight %} + {% if this.smooth_factor is not none %} + , + {% endif %} + onEachFeature: {{this.get_name()}}_onEachFeature + {% endif %} + } + {% endif %} + ) + {% if this.tooltip %}.bindTooltip("{{this.tooltip.__str__()}}"){% endif %} + .addTo({{this._parent.get_name()}}); + + {% endmacro %} + """) # noqa + + def _get_self_bounds(self): + """ + Computes the bounds of the object itself (not including it's children) + in the form [[lat_min, lon_min], [lat_max, lon_max]]. + + """ + return get_bounds(self.data, lonlat=True) + + def render(self, **kwargs): + super(GeoJsonCss, self).render(**kwargs) + figure = self.get_root() + assert isinstance(figure, Figure), ('You cannot render this Element ' + 'if it is not in a Figure.') + + figure.header.add_child( + JavascriptLink('https://cdn.rawgit.com/albburtsev/Leaflet.geojsonCSS/master/leaflet.geojsoncss.min.js'), # noqa + name='Leaflet.GeoJsonCss.js' + ) + + class TopoJson(Layer): """ Creates a TopoJson object for plotting into a Map. From e6cc1fc282cc133a0e15e49be9a1abec4f0adcf6 Mon Sep 17 00:00:00 2001 From: Andy Challis Date: Tue, 17 Oct 2017 20:18:07 +0100 Subject: [PATCH 2/9] Fixing Sticklers comments Darn Stickler --- folium/features.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/folium/features.py b/folium/features.py index 0355559f5a..54b659992c 100644 --- a/folium/features.py +++ b/folium/features.py @@ -448,7 +448,6 @@ def _get_self_bounds(self): return get_bounds(self.data, lonlat=True) - class GeoJsonCss(Layer): """ Creates a GeoJsonCss object for plotting into a Map. @@ -493,7 +492,7 @@ def __init__(self, data, name=None, overlay=True, control=True, smooth_factor=None, highlight_function=None, tooltip=None): super(GeoJsonCss, self).__init__(name=name, overlay=overlay, - control=control) + control=control) self._name = 'GeoJsonCss' self.tooltip = tooltip if isinstance(data, dict): From 777e8083fbaabc1bb2a13d25735904ec425f0b67 Mon Sep 17 00:00:00 2001 From: Filipe Fernandes Date: Thu, 2 Nov 2017 16:46:42 -0200 Subject: [PATCH 3/9] refactor GeoJsonCss --- examples/GeoJsonCSS.ipynb | 83 +++++++++++++++++--- examples/data/css_demo.geojson | 110 +++++++++++++++++++++++++++ examples/data/metro.png | Bin 0 -> 1821 bytes examples/data/vlad.json | 71 ------------------ folium/__init__.py | 1 - folium/features.py | 133 ++++++--------------------------- folium/utilities.py | 36 ++++++++- 7 files changed, 238 insertions(+), 196 deletions(-) create mode 100644 examples/data/css_demo.geojson create mode 100644 examples/data/metro.png delete mode 100644 examples/data/vlad.json diff --git a/examples/GeoJsonCSS.ipynb b/examples/GeoJsonCSS.ipynb index 1c883ae22a..23e7e3ad33 100644 --- a/examples/GeoJsonCSS.ipynb +++ b/examples/GeoJsonCSS.ipynb @@ -1,40 +1,101 @@ { "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.5.0+46.g35b5179.dirty\n" + ] + } + ], + "source": [ + "import os\n", + "import folium\n", + "\n", + "print(folium.__version__)" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ - "# Implementing the Leaflet-GeoJsonCSS library" + "### Default, no css" ] }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, - "execution_count": 17, + "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "import os\n", - "import folium\n", + "m = folium.Map(\n", + " location=[55.75258, 37.61489],\n", + " zoom_start=14,\n", + " tiles = 'cartodbpositron'\n", + ")\n", + "\n", + "fname = os.path.join('data', 'css_demo.geojson')\n", + "\n", + "folium.GeoJson(fname).add_to(m)\n", + "\n", + "m" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Using the css in the metadata" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
" + ], + "text/plain": [ + "" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "m = folium.Map(\n", + " location=[55.75258, 37.61489],\n", + " zoom_start=14,\n", + " tiles = 'cartodbpositron'\n", + ")\n", "\n", - "m = folium.Map(location=[55.75258, 37.61489], zoom_start=14, tiles = 'cartodbpositron')\n", "\n", - "data = os.path.join('data', 'vlad.json')\n", + "folium.GeoJsonCss(fname).add_to(m)\n", "\n", - "folium.GeoJsonCss(data).add_to(m)\n", "m" ] } @@ -55,7 +116,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.2" + "version": "3.6.3" } }, "nbformat": 4, diff --git a/examples/data/css_demo.geojson b/examples/data/css_demo.geojson new file mode 100644 index 0000000000..ccbef4f8b5 --- /dev/null +++ b/examples/data/css_demo.geojson @@ -0,0 +1,110 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": { + "title": "Kremlin" + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [37.61489152908325,55.752586015356876], + [37.61577129364014,55.7539867694403], + [37.616543769836426,55.75506145183324], + [37.6177453994751,55.75443355110991], + [37.619526386260986,55.753491681072205], + [37.62143611907959,55.75252563689488], + [37.62117862701416,55.75211506087468], + [37.61875391006469,55.750762544596384], + [37.61813163757324,55.749989657097], + [37.61302471160889,55.749035602973365], + [37.612552642822266,55.74907183330299], + [37.6134967803955,55.750641781933986], + [37.61489152908325,55.752586015356876] + ]] + }, + "style": { + "color": "#CC0000", + "weight": 2, + "fill-opacity": 0.6, + "opacity": 1, + "dashArray": "3, 5" + }, + "popupTemplate": "{title}" + }, + { + "type": "Feature", + "properties": { + "title": "Kremlin embankment" + }, + "geometry": { + "type": "MultiLineString", + "coordinates": [[[37.611907,55.747355],[37.612639,55.747611],[37.613671,55.747839],[37.614446,55.748040],[37.616002,55.748446],[37.616364,55.748537],[37.616573,55.748585],[37.616779,55.748627],[37.617038,55.748677],[37.618375,55.748887],[37.620201,55.749173],[37.620494,55.749215],[37.620723,55.749246],[37.621209,55.749296],[37.622037,55.749388],[37.622402,55.749421],[37.622745,55.749461],[37.622990,55.749484],[37.623206,55.749507],[37.623680,55.749562],[37.624266,55.749640]],[[37.624245,55.749770],[37.623771,55.749678],[37.623476,55.749623],[37.623147,55.749577],[37.621484,55.749414],[37.620021,55.749222],[37.618740,55.749021],[37.617359,55.748819],[37.616927,55.748750],[37.616755,55.748721],[37.616592,55.748691],[37.616413,55.748652],[37.616225,55.748608],[37.614894,55.748251],[37.614139,55.748055],[37.613795,55.747971],[37.613487,55.747906],[37.612526,55.747741],[37.612248,55.747656],[37.611791,55.747497]]] + }, + "style": { + "color": "#CC0000", + "opacity": 1, + "weight": 4 + }, + "popupTemplate": "{title}" + }, + { + "type": "Feature", + "properties": { + "title": "Alexandrovskiy sad" + }, + "geometry": { + "type": "Point", + "coordinates": [37.61001, 55.752301] + }, + "style": { + "icon": { + "iconUrl": + "https://github.com/python-visualization/folium/raw/master/examples/data/metro.png", + "iconSize": [32, 32], + "iconAnchor": [16, 16] + } + }, + "popupTemplate": "{title}" + }, + { + "type": "Feature", + "properties": { + "title": "Okhotny ryad" + }, + "geometry": { + "type": "Point", + "coordinates": [37.617317, 55.75725] + }, + "style": { + "icon": { + "iconUrl": + "https://github.com/python-visualization/folium/raw/master/examples/data/metro.png", + "iconSize": [32, 32], + "iconAnchor": [16, 16] + } + }, + "popupTemplate": "{title}" + }, + { + "type": "Feature", + "properties": { + "title": "Ploschad Revolutsii" + }, + "geometry": { + "type": "Point", + "coordinates": [37.622674, 55.756922] + }, + "style": { + "icon": { + "iconUrl": + "https://github.com/python-visualization/folium/raw/master/examples/data/metro.png", + "iconSize": [32, 32], + "iconAnchor": [16, 16] + } + }, + "popupTemplate": "{title}" + } + ] +} diff --git a/examples/data/metro.png b/examples/data/metro.png new file mode 100644 index 0000000000000000000000000000000000000000..2428344038e9ff2cdf4e1e7488b071f889dfa6dd GIT binary patch literal 1821 zcmV+&2jcjNP)RB1mFz4hdtxTJU@b0`NU@&TPKnFNdB5;*Wa)bEJ9E+y&*C z6Q&ep$WLLKm*KB@5VLeSRM+w$4G+P|6O{J6fjj&+C@aSWe&NJaVZq|VE$0BoN09Bk zyXleq=k9d*riHHX)vq|$@xGHL(iohWaA&%@+}X}fh0e;kyt^p%YDTkSh$ZHKy8+w2 z^#v_rM^NX9@E#$ zw6->?b2(gZ4>l8GeNUmYa%pW+J?hnrX2lQ-F~ye0)h-Zh$kx0?u7JOC6?WZvI=Z{D zIQ+6Q;(foP=AISQtyoFnr7hSrXFX4$vvR7bN4=WStQca6iP-Xx*S}xD99S@aSrEsc zCGZJ;vW@QZ!sWa{e){_v)9*dS2ooaX*W=H{EZq4Bn~_Z8(d zD~4ENBDOr_1(<)mKzLhOW;?k&;f5y}jbozx6ux(Hy-8~;Giz&z1_sH$eU$p&uFZ=VQlI!-O8ilkbvkTC7)O?xGl1S&0(Xvv^@h)YXaKdJH=}f=d!?;8Q3Th)Iar z+Neo4qbRks5)o5OYwBSthc}tSKi(>aSYnDT4_qlmp7Qnq>zuBZP*TQPFb12+Ft+Dc zWYhIV?d{k=TQPJE4XT%01CPwtzlKzJ{g?EPj8cjs=Fe>)2|Y?3=@wQ$zFXy+ zV`_4O@EZ@OwJ)hhmnCj{kLtUc7~ArqSYnEe0Zc;!#16@VZsbVL4Yo1*11pvz%{us+@)%(D)~$?ec#K)|=aCEyP_c3q`JJy30EsaqdSWoil?}M@C_ZJZ zk4;zEVhpG2YN%gxKfL=6o*&?QmZ)k5qfb7;QDg9c8=CK8JTVHLl~YYU>eURM@59+M zDQi{AtQK1y7|&-sPEG;N2jamfI$mkLTjGOnk=?j~+;8?Wn7&*Fazz|q09!o+tR=g4 zEfxuGeD$YDsw-5>{pn5exg00k&Rm@RYr4Uj8gNc*qTlYrS)cP!^p3m%DtBjRZyc#_ zaHETtx@)b`re$uVey)4GYUcgGbOVIIoS`|NK52`^(B%sdN8pgapz{^Egp|YO)xhPm zG5TY#{`1%KF=b^WVNj~=Ix`RG^??YuaHLS!*%V|pGR+rIRIVn&$B_X8&RF(O{title}" - }, - { - "type": "Feature", - "properties": { - "title": "Vladimir's favourite road" - }, - "geometry": { - "type": "MultiLineString", - "coordinates": [[[37.611907,55.747355],[37.612639,55.747611],[37.613671,55.747839],[37.614446,55.748040],[37.616002,55.748446],[37.616364,55.748537],[37.616573,55.748585],[37.616779,55.748627],[37.617038,55.748677],[37.618375,55.748887],[37.620201,55.749173],[37.620494,55.749215],[37.620723,55.749246],[37.621209,55.749296],[37.622037,55.749388],[37.622402,55.749421],[37.622745,55.749461],[37.622990,55.749484],[37.623206,55.749507],[37.623680,55.749562],[37.624266,55.749640]],[[37.624245,55.749770],[37.623771,55.749678],[37.623476,55.749623],[37.623147,55.749577],[37.621484,55.749414],[37.620021,55.749222],[37.618740,55.749021],[37.617359,55.748819],[37.616927,55.748750],[37.616755,55.748721],[37.616592,55.748691],[37.616413,55.748652],[37.616225,55.748608],[37.614894,55.748251],[37.614139,55.748055],[37.613795,55.747971],[37.613487,55.747906],[37.612526,55.747741],[37.612248,55.747656],[37.611791,55.747497]]] - }, - "style": { - "color": "#CC0000", - "opacity": 1, - "weight": 4 - }, - "popupTemplate": "{title}" - }, - { - "type": "Feature", - "properties": { - "title": "Vladamir's house" - }, - "geometry": { - "type": "Point", - "coordinates": [37.61001, 55.752301] - }, - "style": { - "icon": { - "iconUrl": "http://downloadicons.net/sites/default/files/small-house-with-a-chimney-icon-70053.png", - "iconSize": [32, 32], - "iconAnchor": [16, 16] - } - }, - "popupTemplate": "{title}" - } - ] -} \ No newline at end of file diff --git a/folium/__init__.py b/folium/__init__.py index 38a7c39f60..eb1d3c73ea 100644 --- a/folium/__init__.py +++ b/folium/__init__.py @@ -53,7 +53,6 @@ 'DivIcon', 'GeoJson', 'GeoJsonCss', - 'GeoJsonStyle', 'LatLngPopup', 'MarkerCluster', 'Vega', diff --git a/folium/features.py b/folium/features.py index 54b659992c..90763baed2 100644 --- a/folium/features.py +++ b/folium/features.py @@ -14,13 +14,11 @@ from branca.utilities import (_locations_tolist, _parse_size, image_to_url, iter_points, none_max, none_min) # noqa from folium.map import FeatureGroup, Icon, Layer, Marker -from folium.utilities import get_bounds +from folium.utilities import geojsonlike2dict, get_bounds from folium.vector_layers import PolyLine from jinja2 import Template -import requests - from six import binary_type, text_type @@ -343,35 +341,7 @@ class GeoJson(Layer): def __init__(self, data, style_function=None, name=None, overlay=True, control=True, smooth_factor=None, highlight_function=None, tooltip=None): - super(GeoJson, self).__init__(name=name, overlay=overlay, - control=control) - self._name = 'GeoJson' - self.tooltip = tooltip - if isinstance(data, dict): - self.embed = True - self.data = data - elif isinstance(data, text_type) or isinstance(data, binary_type): - self.embed = True - if data.lower().startswith(('http:', 'ftp:', 'https:')): - self.data = requests.get(data).json() - elif data.lstrip()[0] in '[{': # This is a GeoJSON inline string - self.data = json.loads(data) - else: # This is a filename - with open(data) as f: - self.data = json.loads(f.read()) - elif data.__class__.__name__ in ['GeoDataFrame', 'GeoSeries']: - self.embed = True - if hasattr(data, '__geo_interface__'): - # We have a GeoPandas 0.2 object. - self.data = json.loads(json.dumps(data.to_crs(epsg='4326').__geo_interface__)) # noqa - elif hasattr(data, 'columns'): - # We have a GeoDataFrame 0.1 - self.data = json.loads(data.to_crs(epsg='4326').to_json()) - else: - msg = 'Unable to transform this object to a GeoJSON.' - raise ValueError(msg) - else: - raise ValueError('Unhandled object {!r}.'.format(data)) + super(GeoJson, self).__init__(name=name, overlay=overlay, control=control) self.style_function = style_function or (lambda x: {}) @@ -379,6 +349,11 @@ def __init__(self, data, style_function=None, name=None, self.highlight_function = highlight_function or (lambda x: {}) + self._name = 'GeoJson' + self.tooltip = tooltip + self.style_function = style_function + self.highlight = highlight_function is not None + self.highlight_function = highlight_function self.smooth_factor = smooth_factor self._template = Template(u""" @@ -448,89 +423,31 @@ def _get_self_bounds(self): return get_bounds(self.data, lonlat=True) -class GeoJsonCss(Layer): +class GeoJsonCss(GeoJson): """ - Creates a GeoJsonCss object for plotting into a Map. - - Parameters - ---------- - data: file, dict or str. - The GeoJSON data you want to plot. - * If file, then data will be read in the file and fully - embedded in Leaflet's JavaScript. - * 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. - highlight_function: function, default None - Function mapping a GeoJson Feature to a style dict for mouse events. - name : string, default None - The name of the Layer, as it will appear in LayerControls - overlay : bool, default False - Adds the layer as an optional overlay (True) or the base layer (False). - control : bool, default True - Whether the Layer will be included in LayerControls - smooth_factor: float, default None - How much to simplify the polyline on each zoom level. More means - better performance and smoother look, and less means more accurate - representation. Leaflet defaults to 1.0. - - Examples - -------- - >>> # Providing file that shall be embedded. - >>> GeoJsonCss(open('foo.json')) - >>> # Providing filename that shall not be embedded. - >>> GeoJsonCss('foo.json') - >>> # Providing dict. - >>> GeoJsonCss(json.load(open('foo.json'))) - >>> # Providing string. - >>> GeoJsonCss(open('foo.json').read()) - - >>> GeoJsonCss(geojson_with_css) + `GeoJsonCss` augumets GeoJson by using properties in the GeoJson file to style + the document. + See `GeoJson` for the docs and + https://github.com/albburtsev/Leaflet.geojsonCSS + for more Information on the plugin. """ - def __init__(self, data, name=None, - overlay=True, control=True, smooth_factor=None, - highlight_function=None, tooltip=None): - super(GeoJsonCss, self).__init__(name=name, overlay=overlay, + def __init__(self, data, name=None, overlay=True, control=True, + smooth_factor=None, highlight_function=None, tooltip=None): + super(GeoJsonCss, self).__init__(data=data, name=name, overlay=overlay, control=control) - self._name = 'GeoJsonCss' - self.tooltip = tooltip - if isinstance(data, dict): - self.embed = True - self.data = data - elif isinstance(data, text_type) or isinstance(data, binary_type): - self.embed = True - if data.lower().startswith(('http:', 'ftp:', 'https:')): - self.data = requests.get(data).json() - elif data.lstrip()[0] in '[{': # This is a GeoJSON inline string - self.data = json.loads(data) - else: # This is a filename - with open(data) as f: - self.data = json.loads(f.read()) - elif data.__class__.__name__ in ['GeoDataFrame', 'GeoSeries']: - self.embed = True - if hasattr(data, '__geo_interface__'): - # We have a GeoPandas 0.2 object. - self.data = json.loads(json.dumps(data.to_crs(epsg='4326').__geo_interface__)) # noqa - elif hasattr(data, 'columns'): - # We have a GeoDataFrame 0.1 - self.data = json.loads(data.to_crs(epsg='4326').to_json()) - else: - msg = 'Unable to transform this object to a GeoJSON.' - raise ValueError(msg) - else: - raise ValueError('Unhandled object {!r}.'.format(data)) - - self.highlight = highlight_function is not None - if highlight_function is None: def highlight_function(x): return {} + self._name = 'GeoJsonCss' + self.tooltip = tooltip + self.highlight = highlight_function is not None self.highlight_function = highlight_function - self.smooth_factor = smooth_factor + self.data = geojsonlike2dict(data) + self._template = Template(u""" {% macro script(this, kwargs) %} @@ -570,14 +487,6 @@ def highlight_function(x): {% endmacro %} """) # noqa - def _get_self_bounds(self): - """ - Computes the bounds of the object itself (not including it's children) - in the form [[lat_min, lon_min], [lat_max, lon_max]]. - - """ - return get_bounds(self.data, lonlat=True) - def render(self, **kwargs): super(GeoJsonCss, self).render(**kwargs) figure = self.get_root() diff --git a/folium/utilities.py b/folium/utilities.py index b042bead01..912ba731fa 100644 --- a/folium/utilities.py +++ b/folium/utilities.py @@ -9,6 +9,7 @@ import zlib import numpy as np +import requests from six import binary_type, text_type @@ -129,7 +130,7 @@ def _is_url(url): """Check to see if `url` has a valid protocol.""" try: return urlparse(url).scheme in _VALID_URLS - except: + except Exception: return False @@ -165,6 +166,10 @@ def write_png(data, origin='upper', colormap=None): PNG formatted byte string """ + if np is None: + raise ImportError('The NumPy package is required ' + ' for this functionality') + if colormap is None: def colormap(x): return (x, x, x, 1) @@ -359,3 +364,32 @@ def get_bounds(locations, lonlat=False): if lonlat: bounds = _locations_mirror(bounds) return bounds + + +def geojsonlike2dict(data): + """Convert GeoJSON data to a Python dictionary.""" + # If it is already a dict, do nothing. + if isinstance(data, dict): + return data + # Read from GeoPandas. + elif data.__class__.__name__ in ['GeoDataFrame', 'GeoSeries']: + if hasattr(data, '__geo_interface__'): + # GeoPandas 0.2 object. + return json.loads(json.dumps(data.to_crs(epsg='4326').__geo_interface__)) + elif hasattr(data, 'columns'): + # GeoDataFrame 0.1 + return json.loads(data.to_crs(epsg='4326').to_json()) + else: + raise ValueError('Do not know how convert this GeoPandas object {!r} to a GeoJSON.'.format(data)) + # Read from GeoJSON inline string. + elif isinstance(data, (text_type, binary_type)) and data.lstrip()[0] in '[{': + return json.loads(data) + # Read from remote URL. + elif isinstance(data, (text_type, binary_type)) and data.lower().startswith(('http:', 'ftp:', 'https:')): + return requests.get(data).json() + # Assume it is a from local file and let open/json.loads deal with it. + elif isinstance(data, (text_type, binary_type)): + with open(data) as f: + return json.loads(f.read()) + else: + raise ValueError('Do not know how to transform {!r} to a GeoJSON.'.format(data)) From 3569edf6aa0d4791aa5ee29e390621868048615f Mon Sep 17 00:00:00 2001 From: Filipe Fernandes Date: Thu, 2 Nov 2017 17:03:09 -0200 Subject: [PATCH 4/9] simplify template --- folium/features.py | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/folium/features.py b/folium/features.py index 90763baed2..aad63179e6 100644 --- a/folium/features.py +++ b/folium/features.py @@ -343,19 +343,15 @@ def __init__(self, data, style_function=None, name=None, highlight_function=None, tooltip=None): super(GeoJson, self).__init__(name=name, overlay=overlay, control=control) - self.style_function = style_function or (lambda x: {}) - - self.highlight = highlight_function is not None - - self.highlight_function = highlight_function or (lambda x: {}) - self._name = 'GeoJson' self.tooltip = tooltip - self.style_function = style_function self.highlight = highlight_function is not None - self.highlight_function = highlight_function + self.highlight_function = highlight_function or (lambda x: {}) + self.style_function = style_function or (lambda x: {}) self.smooth_factor = smooth_factor + self.data = geojsonlike2dict(data) + self._template = Template(u""" {% macro script(this, kwargs) %} @@ -373,7 +369,7 @@ def __init__(self, data, style_function=None, name=None, {% endif %} var {{this.get_name()}} = L.geoJson( - {% if this.embed %}{{this.style_data()}}{% else %}"{{this.data}}"{% endif %} + {{this.style_data()}} {% if this.smooth_factor is not none or this.highlight %} , { {% if this.smooth_factor is not none %} @@ -436,14 +432,11 @@ def __init__(self, data, name=None, overlay=True, control=True, smooth_factor=None, highlight_function=None, tooltip=None): super(GeoJsonCss, self).__init__(data=data, name=name, overlay=overlay, control=control) - if highlight_function is None: - def highlight_function(x): - return {} self._name = 'GeoJsonCss' self.tooltip = tooltip self.highlight = highlight_function is not None - self.highlight_function = highlight_function + self.highlight_function = highlight_function or (lambda x: {}) self.smooth_factor = smooth_factor self.data = geojsonlike2dict(data) From ede2595a9190f35937812d6f4f974bec3f1a92ff Mon Sep 17 00:00:00 2001 From: Filipe Fernandes Date: Thu, 2 Nov 2017 18:16:41 -0200 Subject: [PATCH 5/9] fix lints --- examples/GeoJsonCSS.ipynb | 10 +-- examples/Plugins.ipynb | 165 +++++++++++++++++++++----------------- 2 files changed, 95 insertions(+), 80 deletions(-) diff --git a/examples/GeoJsonCSS.ipynb b/examples/GeoJsonCSS.ipynb index 23e7e3ad33..e0a6999864 100644 --- a/examples/GeoJsonCSS.ipynb +++ b/examples/GeoJsonCSS.ipynb @@ -9,7 +9,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "0.5.0+46.g35b5179.dirty\n" + "0.5.0+100.g3569edf.dirty\n" ] } ], @@ -35,10 +35,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 2, @@ -75,10 +75,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 3, diff --git a/examples/Plugins.ipynb b/examples/Plugins.ipynb index fc16b1b1d1..80fb9b9b22 100644 --- a/examples/Plugins.ipynb +++ b/examples/Plugins.ipynb @@ -9,7 +9,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "0.5.0+97.ged1a58f.dirty\n" + "0.5.0+100.g3569edf.dirty\n" ] } ], @@ -58,10 +58,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 2, @@ -104,10 +104,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 3, @@ -153,10 +153,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 4, @@ -189,10 +189,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 5, @@ -240,10 +240,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 6, @@ -281,10 +281,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 7, @@ -293,9 +293,6 @@ } ], "source": [ - "from folium import plugins\n", - "\n", - "\n", "m = folium.Map(\n", " location=[35.68159659061569, 139.76451516151428],\n", " zoom_start=16\n", @@ -389,10 +386,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 8, @@ -401,31 +398,34 @@ } ], "source": [ - "from folium import plugins\n", - "\n", - "\n", "points = [\n", - " {\"time\":'2017-06-02',\n", - " \"popup\":\"

address1

\",\n", - " \"coordinates\":[-2.548828, 51.467697]},\n", - " \n", - " {\"time\":'2017-07-02',\n", - " \"popup\":\"

address2

\",\n", - " \"coordinates\":[-0.087891, 51.536086]},\n", - " \n", - " {\"time\":'2017-08-02',\n", - " \"popup\":\"

address3

\",\n", - " \"coordinates\":[-6.240234, 53.383328]},\n", - " \n", - " {\"time\":'2017-09-02',\n", - " \"popup\":\"

address4

\",\n", - " \"coordinates\":[-1.40625, 60.261617]},\n", - " \n", - " {\"time\":'2017-10-02',\n", - " \"popup\":\"\"\"\n", + " {\n", + " 'time': '2017-06-02',\n", + " 'popup': '

address1

',\n", + " 'coordinates': [-2.548828, 51.467697]\n", + " },\n", + " {\n", + " 'time': '2017-07-02',\n", + " 'popup': '

address2

',\n", + " 'coordinates': [-0.087891, 51.536086]\n", + " },\n", + " {\n", + " 'time': '2017-08-02',\n", + " 'popup': '

address3

',\n", + " 'coordinates': [-6.240234, 53.383328]\n", + " },\n", + " {\n", + " 'time': '2017-09-02',\n", + " 'popup': '

address4

',\n", + " 'coordinates': [-1.40625, 60.261617]\n", + " },\n", + " {\n", + " 'time': '2017-10-02',\n", + " 'popup': \"\"\"\n", + "

\n", " \n", - " \n", - " \n", + " \n", + " \n", " \n", " \n", " \n", @@ -438,54 +438,69 @@ " \n", " \n", " \n", - "
FirstnameLastnameFirstLastAge
Jackson94
\"\"\",\n", - " \"coordinates\":[-1.516113, 53.800651]}\n", + "\n", + "\"\"\",\n", + " 'coordinates': [-1.516113, 53.800651]\n", + " }\n", "]\n", "\n", - "features = [{\n", - " \"type\": \"Feature\",\n", - " \"geometry\": {\n", - " \"type\": \"Point\",\n", - " \"coordinates\": point['coordinates'],\n", - " },\n", - " \"properties\": {\n", - " \"time\": point['time'],\n", - " \"popup\": point['popup'],\n", - " \"id\":\"house\",\n", - " 'icon':'marker',\n", - " 'iconstyle':{\n", - " 'iconUrl': 'http://downloadicons.net/sites/default/files/small-house-with-a-chimney-icon-70053.png',\n", - " 'iconSize': [20, 20]\n", - " }\n", - " }\n", - " } for point in points]\n", - "\n", - "features.append({\n", + "features = [\n", + " {\n", + " 'type': 'Feature',\n", + " 'geometry': {\n", + " 'type': 'Point',\n", + " 'coordinates': point['coordinates'],\n", + " },\n", + " 'properties': {\n", + " 'time': point['time'],\n", + " 'popup': point['popup'],\n", + " 'id': 'house',\n", + " 'icon': 'marker',\n", + " 'iconstyle': {\n", + " 'iconUrl': 'http://downloadicons.net/sites/default/files/small-house-with-a-chimney-icon-70053.png',\n", + " 'iconSize': [20, 20]\n", + " }\n", + " }\n", + " } for point in points\n", + "]\n", + "\n", + "\n", + "features.append(\n", + " {\n", " 'type': 'Feature',\n", " 'geometry': {\n", " 'type': 'LineString',\n", - " 'coordinates': [[-2.548828, 51.467697], [-0.087891, 51.536086], \n", - " [-6.240234, 53.383328], [-1.40625, 60.261617],\n", - " [-1.516113, 53.800651]\n", - " ],\n", + " 'coordinates': [\n", + " [-2.548828, 51.467697],\n", + " [-0.087891, 51.536086],\n", + " [-6.240234, 53.383328],\n", + " [-1.40625, 60.261617],\n", + " [-1.516113, 53.800651]\n", + " ],\n", " },\n", " 'properties': {\n", - " 'popup':'Current address',\n", - " 'times': ['2017-06-02', '2017-07-02',\n", - " '2017-08-02', '2017-09-02',\n", - " '2017-10-02'],\n", - " 'icon':'circle',\n", - " 'iconstyle':{\n", + " 'popup': 'Current address',\n", + " 'times': [\n", + " '2017-06-02',\n", + " '2017-07-02',\n", + " '2017-08-02',\n", + " '2017-09-02',\n", + " '2017-10-02'\n", + " ],\n", + " 'icon': 'circle',\n", + " 'iconstyle': {\n", " 'fillColor': 'green',\n", " 'fillOpacity': 0.6,\n", " 'stroke': 'false',\n", " 'radius': 13\n", " },\n", - " 'style': {'weight':0\n", + " 'style': {\n", + " 'weight': 0\n", " },\n", - " 'id':'man'\n", + " 'id': 'man'\n", " }\n", - " })\n", + " }\n", + ")\n", "\n", "m = folium.Map(\n", " location=[56.096555, -3.64746],\n", From bfefb02b85c9188ec27b736d67b26f99b079f178 Mon Sep 17 00:00:00 2001 From: Filipe Fernandes Date: Thu, 2 Nov 2017 18:54:01 -0200 Subject: [PATCH 6/9] merge geojsoncss into geojson --- examples/GeoJsonCSS.ipynb | 16 +++-- folium/__init__.py | 3 +- folium/features.py | 119 ++++++++++---------------------------- 3 files changed, 42 insertions(+), 96 deletions(-) diff --git a/examples/GeoJsonCSS.ipynb b/examples/GeoJsonCSS.ipynb index e0a6999864..4b65ce9bd5 100644 --- a/examples/GeoJsonCSS.ipynb +++ b/examples/GeoJsonCSS.ipynb @@ -9,7 +9,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "0.5.0+100.g3569edf.dirty\n" + "0.5.0+101.gede2595.dirty\n" ] } ], @@ -35,10 +35,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 2, @@ -57,6 +57,8 @@ "\n", "folium.GeoJson(fname).add_to(m)\n", "\n", + "m.save(os.path.join('results', 'GeoJsonCSS0.html'))\n", + "\n", "m" ] }, @@ -75,10 +77,10 @@ { "data": { "text/html": [ - "
" + "
" ], "text/plain": [ - "" + "" ] }, "execution_count": 3, @@ -94,7 +96,9 @@ ")\n", "\n", "\n", - "folium.GeoJsonCss(fname).add_to(m)\n", + "folium.GeoJson(fname, geojsoncss=True).add_to(m)\n", + "\n", + "m.save(os.path.join('results', 'GeoJsonCSS1.html'))\n", "\n", "m" ] diff --git a/folium/__init__.py b/folium/__init__.py index eb1d3c73ea..0581e2de5b 100644 --- a/folium/__init__.py +++ b/folium/__init__.py @@ -9,7 +9,7 @@ from folium._version import get_versions from folium.features import ( - ClickForMarker, ColorLine, CustomIcon, DivIcon, GeoJson, GeoJsonCss, + ClickForMarker, ColorLine, CustomIcon, DivIcon, GeoJson, LatLngPopup, RegularPolygonMarker, TopoJson, Vega, VegaLite, ) @@ -52,7 +52,6 @@ 'CustomIcon', 'DivIcon', 'GeoJson', - 'GeoJsonCss', 'LatLngPopup', 'MarkerCluster', 'Vega', diff --git a/folium/features.py b/folium/features.py index aad63179e6..4ba3c6b2ab 100644 --- a/folium/features.py +++ b/folium/features.py @@ -307,6 +307,9 @@ class GeoJson(Layer): * If str, then data will be passed to the JavaScript as-is. style_function: function, default None Function mapping a GeoJson Feature to a style dict. + style_function will overwrite `geojsoncss`. + geojsoncss: bool, default False + If True folium will try to read style data from the GeoJson object. highlight_function: function, default None Function mapping a GeoJson Feature to a style dict for mouse events. name : string, default None @@ -340,15 +343,16 @@ class GeoJson(Layer): """ def __init__(self, data, style_function=None, name=None, overlay=True, control=True, smooth_factor=None, - highlight_function=None, tooltip=None): + highlight_function=None, tooltip=None, geojsoncss=False): super(GeoJson, self).__init__(name=name, overlay=overlay, control=control) self._name = 'GeoJson' self.tooltip = tooltip self.highlight = highlight_function is not None self.highlight_function = highlight_function or (lambda x: {}) - self.style_function = style_function or (lambda x: {}) + self.style_function = style_function self.smooth_factor = smooth_factor + self.geojsoncss = geojsoncss self.data = geojsonlike2dict(data) @@ -368,7 +372,7 @@ def __init__(self, data, style_function=None, name=None, }; {% endif %} - var {{this.get_name()}} = L.geoJson( + var {{this.get_name()}} = L.geoJson{% if this.geojsoncss %}.css{% endif %}( {{this.style_data()}} {% if this.smooth_factor is not none or this.highlight %} , { @@ -387,28 +391,40 @@ def __init__(self, data, style_function=None, name=None, ) {% if this.tooltip %}.bindTooltip("{{this.tooltip.__str__()}}"){% endif %} .addTo({{this._parent.get_name()}}); - {{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;}); + {% if this.style_function %}{{this.get_name()}}.setStyle(function(feature) {return feature.properties.style;});{% endif %} {% endmacro %} """) # noqa + def render(self, **kwargs): + super(GeoJson, self).render(**kwargs) + figure = self.get_root() + assert isinstance(figure, Figure), ('You cannot render this Element ' + 'if it is not in a Figure.') + if self.geojsoncss: + figure.header.add_child( + JavascriptLink('https://cdn.rawgit.com/albburtsev/Leaflet.geojsonCSS/master/leaflet.geojsoncss.min.js'), # noqa + name='Leaflet.GeoJsonCss.js' + ) + def style_data(self): """ Applies `self.style_function` to each feature of `self.data` and returns a corresponding JSON output. """ - if 'features' not in self.data.keys(): - # Catch case when GeoJSON is just a single Feature or a geometry. - if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa - # Catch case when GeoJSON is just a geometry. - 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 - return json.dumps(self.data, sort_keys=True) + if self.style_function: + if 'features' not in self.data.keys(): + # Catch case when GeoJSON is just a single Feature or a geometry. + if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa + # Catch case when GeoJSON is just a geometry. + 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 + return self.data def _get_self_bounds(self): """ @@ -419,79 +435,6 @@ def _get_self_bounds(self): return get_bounds(self.data, lonlat=True) -class GeoJsonCss(GeoJson): - """ - `GeoJsonCss` augumets GeoJson by using properties in the GeoJson file to style - the document. - See `GeoJson` for the docs and - https://github.com/albburtsev/Leaflet.geojsonCSS - for more Information on the plugin. - - """ - def __init__(self, data, name=None, overlay=True, control=True, - smooth_factor=None, highlight_function=None, tooltip=None): - super(GeoJsonCss, self).__init__(data=data, name=name, overlay=overlay, - control=control) - - self._name = 'GeoJsonCss' - self.tooltip = tooltip - self.highlight = highlight_function is not None - self.highlight_function = highlight_function or (lambda x: {}) - self.smooth_factor = smooth_factor - - self.data = geojsonlike2dict(data) - - self._template = Template(u""" - {% macro script(this, kwargs) %} - - {% if this.highlight %} - {{this.get_name()}}_onEachFeature = function onEachFeature(feature, layer) { - layer.on({ - mouseout: function(e) { - e.target.setStyle(e.target.feature.properties.style);}, - mouseover: function(e) { - e.target.setStyle(e.target.feature.properties.highlight);}, - click: function(e) { - {{this._parent.get_name()}}.fitBounds(e.target.getBounds());} - }); - }; - {% endif %} - - var {{this.get_name()}} = L.geoJson.css( - {{this.data}} - {% if this.smooth_factor is not none or this.highlight %} - , { - {% if this.smooth_factor is not none %} - smoothFactor:{{this.smooth_factor}} - {% endif %} - - {% if this.highlight %} - {% if this.smooth_factor is not none %} - , - {% endif %} - onEachFeature: {{this.get_name()}}_onEachFeature - {% endif %} - } - {% endif %} - ) - {% if this.tooltip %}.bindTooltip("{{this.tooltip.__str__()}}"){% endif %} - .addTo({{this._parent.get_name()}}); - - {% endmacro %} - """) # noqa - - def render(self, **kwargs): - super(GeoJsonCss, self).render(**kwargs) - figure = self.get_root() - assert isinstance(figure, Figure), ('You cannot render this Element ' - 'if it is not in a Figure.') - - figure.header.add_child( - JavascriptLink('https://cdn.rawgit.com/albburtsev/Leaflet.geojsonCSS/master/leaflet.geojsoncss.min.js'), # noqa - name='Leaflet.GeoJsonCss.js' - ) - - class TopoJson(Layer): """ Creates a TopoJson object for plotting into a Map. From f0feb90ba52115b2088dbcca59e2f2754a190aa3 Mon Sep 17 00:00:00 2001 From: Filipe Fernandes Date: Thu, 2 Nov 2017 18:56:40 -0200 Subject: [PATCH 7/9] fix bad merge --- folium/utilities.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/folium/utilities.py b/folium/utilities.py index 912ba731fa..dcf85a870e 100644 --- a/folium/utilities.py +++ b/folium/utilities.py @@ -166,9 +166,6 @@ def write_png(data, origin='upper', colormap=None): PNG formatted byte string """ - if np is None: - raise ImportError('The NumPy package is required ' - ' for this functionality') if colormap is None: def colormap(x): From ee84583c876e52f0506b56dc6fbf0d09cae26a49 Mon Sep 17 00:00:00 2001 From: Filipe Fernandes Date: Fri, 17 Nov 2017 15:12:34 -0200 Subject: [PATCH 8/9] fix lint --- folium/utilities.py | 1 + 1 file changed, 1 insertion(+) diff --git a/folium/utilities.py b/folium/utilities.py index dcf85a870e..60d8f5b30b 100644 --- a/folium/utilities.py +++ b/folium/utilities.py @@ -9,6 +9,7 @@ import zlib import numpy as np + import requests from six import binary_type, text_type From fc34889a646ac9fff56a54e25f36e74b41adfe92 Mon Sep 17 00:00:00 2001 From: Filipe Fernandes Date: Fri, 17 Nov 2017 16:04:43 -0200 Subject: [PATCH 9/9] fix bug and docstring --- folium/features.py | 35 +++++++++++++++-------------------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/folium/features.py b/folium/features.py index 4ba3c6b2ab..97ea216f2d 100644 --- a/folium/features.py +++ b/folium/features.py @@ -295,7 +295,6 @@ def render(self, **kwargs): class GeoJson(Layer): """ Creates a GeoJson object for plotting into a Map. - Parameters ---------- data: file, dict or str. @@ -307,9 +306,10 @@ class GeoJson(Layer): * If str, then data will be passed to the JavaScript as-is. style_function: function, default None Function mapping a GeoJson Feature to a style dict. - style_function will overwrite `geojsoncss`. + style_function will overwrite the `geojsoncss` in the GeoJSON. geojsoncss: bool, default False If True folium will try to read style data from the GeoJson object. + See https://github.com/albburtsev/Leaflet.geojsonCSS for more information. highlight_function: function, default None Function mapping a GeoJson Feature to a style dict for mouse events. name : string, default None @@ -333,7 +333,6 @@ class GeoJson(Layer): >>> GeoJson(json.load(open('foo.json'))) >>> # Providing string. >>> GeoJson(open('foo.json').read()) - >>> # Provide a style_function that color all states green but Alabama. >>> style_function = lambda x: {'fillColor': '#0000ff' if ... x['properties']['name']=='Alabama' else @@ -348,14 +347,13 @@ def __init__(self, data, style_function=None, name=None, self._name = 'GeoJson' self.tooltip = tooltip + self.data = geojsonlike2dict(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.style_function = style_function self.smooth_factor = smooth_factor self.geojsoncss = geojsoncss - self.data = geojsonlike2dict(data) - self._template = Template(u""" {% macro script(this, kwargs) %} @@ -411,26 +409,23 @@ def style_data(self): """ Applies `self.style_function` to each feature of `self.data` and returns a corresponding JSON output. - """ - if self.style_function: - if 'features' not in self.data.keys(): - # Catch case when GeoJSON is just a single Feature or a geometry. - if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa - # Catch case when GeoJSON is just a geometry. - 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 - return self.data + if 'features' not in self.data.keys(): + # Catch case when GeoJSON is just a single Feature or a geometry. + if not (isinstance(self.data, dict) and 'geometry' in self.data.keys()): # noqa + # Catch case when GeoJSON is just a geometry. + 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 + return json.dumps(self.data, sort_keys=True) def _get_self_bounds(self): """ Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]]. - """ return get_bounds(self.data, lonlat=True)