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 c40aca9c20..b493f1094e 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 035ef20dc4..dd3ad1b7e9 100644 --- a/folium/features.py +++ b/folium/features.py @@ -456,6 +456,148 @@ 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.