Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions examples/GeoJsonCSS.ipynb

Large diffs are not rendered by default.

165 changes: 90 additions & 75 deletions examples/Plugins.ipynb

Large diffs are not rendered by default.

110 changes: 110 additions & 0 deletions examples/data/css_demo.geojson
Original file line number Diff line number Diff line change
@@ -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": "<strong>{title}</strong>"
},
{
"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}"
}
]
}
Binary file added examples/data/metro.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 0 additions & 1 deletion folium/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@
'CustomIcon',
'DivIcon',
'GeoJson',
'GeoJsonStyle',
'LatLngPopup',
'MarkerCluster',
'Vega',
Expand Down
66 changes: 24 additions & 42 deletions folium/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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) %}
Expand All @@ -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 %}
Expand All @@ -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.
Expand All @@ -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)

Expand Down
34 changes: 33 additions & 1 deletion folium/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

import numpy as np

import requests

from six import binary_type, text_type


Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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))