diff --git a/examples/GeoJsonCSS.ipynb b/examples/GeoJsonCSS.ipynb
new file mode 100644
index 0000000000..4b65ce9bd5
--- /dev/null
+++ b/examples/GeoJsonCSS.ipynb
@@ -0,0 +1,128 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "0.5.0+101.gede2595.dirty\n"
+ ]
+ }
+ ],
+ "source": [
+ "import os\n",
+ "import folium\n",
+ "\n",
+ "print(folium.__version__)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Default, no css"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 2,
+ "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",
+ "fname = os.path.join('data', 'css_demo.geojson')\n",
+ "\n",
+ "folium.GeoJson(fname).add_to(m)\n",
+ "\n",
+ "m.save(os.path.join('results', 'GeoJsonCSS0.html'))\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",
+ "\n",
+ "folium.GeoJson(fname, geojsoncss=True).add_to(m)\n",
+ "\n",
+ "m.save(os.path.join('results', 'GeoJsonCSS1.html'))\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.6.3"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
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",
- " | Firstname | \n",
- " Lastname | \n",
+ " First | \n",
+ " Last | \n",
" Age | \n",
"
\n",
" \n",
@@ -438,54 +438,69 @@
" | Jackson | \n",
" 94 | \n",
"
\n",
- "
\"\"\",\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",
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 0000000000..2428344038
Binary files /dev/null and b/examples/data/metro.png differ
diff --git a/folium/__init__.py b/folium/__init__.py
index 2574ff8e48..0581e2de5b 100644
--- a/folium/__init__.py
+++ b/folium/__init__.py
@@ -52,7 +52,6 @@
'CustomIcon',
'DivIcon',
'GeoJson',
- 'GeoJsonStyle',
'LatLngPopup',
'MarkerCluster',
'Vega',
diff --git a/folium/features.py b/folium/features.py
index de8899c6e5..97ea216f2d 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
@@ -297,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.
@@ -309,6 +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 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
@@ -332,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
@@ -342,44 +342,17 @@ 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)
+ highlight_function=None, tooltip=None, geojsoncss=False):
+ 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))
-
+ 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.smooth_factor = smooth_factor
+ self.geojsoncss = geojsoncss
self._template = Template(u"""
{% macro script(this, kwargs) %}
@@ -397,8 +370,8 @@ 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 %}
+ var {{this.get_name()}} = L.geoJson{% if this.geojsoncss %}.css{% endif %}(
+ {{this.style_data()}}
{% if this.smooth_factor is not none or this.highlight %}
, {
{% if this.smooth_factor is not none %}
@@ -416,16 +389,26 @@ 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.
@@ -443,7 +426,6 @@ 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)
diff --git a/folium/utilities.py b/folium/utilities.py
index b042bead01..60d8f5b30b 100644
--- a/folium/utilities.py
+++ b/folium/utilities.py
@@ -10,6 +10,8 @@
import numpy as np
+import requests
+
from six import binary_type, text_type
@@ -129,7 +131,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 +167,7 @@ def write_png(data, origin='upper', colormap=None):
PNG formatted byte string
"""
+
if colormap is None:
def colormap(x):
return (x, x, x, 1)
@@ -359,3 +362,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))