Skip to content

plugin objects definition, with two examples #148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 11, 2015
Merged
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
12 changes: 11 additions & 1 deletion folium/folium.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,16 @@ def fit_bounds(self, bounds, padding_top_left=None,

self.template_vars.update({'fit_bounds': fit_bounds_str})

def add_plugin(self, plugin):
"""Adds a plugin to the map.

Parameters
----------
plugin: folium.plugins object
A plugin to be added to the map. It has to implement the methods
`render_html`, `render_css` and `render_js`.
"""
self.plugins[plugin.name] = plugin

def _auto_bounds(self):
if 'fit_bounds' in self.template_vars:
Expand Down Expand Up @@ -963,7 +973,7 @@ def _build_map(self, html_templ=None, templ_type='string'):
if templ_type == 'string':
html_templ = self.env.from_string(html_templ)

self.HTML = html_templ.render(self.template_vars)
self.HTML = html_templ.render(self.template_vars, plugins=self.plugins)

def create_map(self, path='map.html', plugin_data_out=True, template=None):
"""Write Map output to HTML and data output to JSON if available.
Expand Down
123 changes: 123 additions & 0 deletions folium/plugins/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,124 @@
# -*- coding: utf-8 -*-

from uuid import uuid4
import json

class Plugin():
"""Basic plugin object that does nothing.
Other plugins may inherit from this one."""
def __init__(self):
"""Creates a plugin to append into a map with Map.add_plugin. """
self.name = "Plugin_"+uuid4().hex

def render_html(self):
"""Generates the HTML part of the plugin."""
return ""

def render_css(self):
"""Generates the CSS part of the plugin."""
return ""

def render_js(self):
"""Generates the Javascript part of the plugin."""
return ""
def render_header(self):
"""Generates the Header part of the plugin."""
return ""


class ScrollZoomToggler(Plugin):
"""Adds a button to enable/disable zoom scrolling."""
def __init__(self, zoom_enabled=False):
"""Creates a ScrollZoomToggler plugin to append into a map with
Map.add_plugin.

Parameters
----------
zoom_enabled: bool, default False
Whether the zoom scrolling shall be enabled at display.
"""
self.zoom_enabled = zoom_enabled
self.name = "ScrollZoomToggler_"+uuid4().hex

def render_html(self):
"""Generates the HTML part of the plugin."""
return """<img id="{}" alt="scroll"
src="https://cdnjs.cloudflare.com/ajax/libs/ionicons/1.5.2/png/512/arrow-move.png"
onclick="toggleScroll()"></img>""".format(self.name)

def render_css(self):
"""Generates the CSS part of the plugin."""
return """
#"""+self.name+""" {
position:absolute;
width:35px;
bottom:10px;
height:35px;
left:10px;
background-color:#fff;
text-align:center;
line-height:35px;
vertical-align: middle;
}
"""

def render_js(self):
"""Generates the Javascript part of the plugin."""
out = """
map.scrollEnabled = true;

var toggleScroll = function() {
if (map.scrollEnabled) {
map.scrollEnabled = false;
map.scrollWheelZoom.disable();
}
else {
map.scrollEnabled = true;
map.scrollWheelZoom.enable();
}
};
"""
if not self.zoom_enabled:
out += "\n toggleScroll();"
return out

class MarkerCluster(Plugin):
"""Adds a MarkerCluster layer on the map."""
def __init__(self, data):
"""Creates a MarkerCluster plugin to append into a map with
Map.add_plugin.

Parameters
----------
data: list of list or array of shape (n,3).
Data points of the form [[lat, lng, popup]].
"""
self.data = [tuple(x) for x in data]
self.name = "MarkerCluster_"+uuid4().hex

def render_header(self):
"""Generates the HTML part of the plugin."""
return """
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/0.4.0/MarkerCluster.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/0.4.0/MarkerCluster.Default.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/0.4.0/leaflet.markercluster.js"></script>
"""

def render_js(self):
"""Generates the Javascript part of the plugin."""
out = """
var addressPoints = """+json.dumps(self.data)+""";

var markers = L.markerClusterGroup();

for (var i = 0; i < addressPoints.length; i++) {
var a = addressPoints[i];
var title = a[2];
var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
marker.bindPopup(title);
markers.addLayer(marker);
}

map.addLayer(markers);
"""
return out
16 changes: 16 additions & 0 deletions folium/templates/fol_template.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@

<link rel="stylesheet" href="https://birdage.github.io/Leaflet.awesome-markers/dist/leaflet.awesome.rotate.css">

{% for name, plugin in plugins.items() %}
{{plugin.render_header()}}
{% endfor %}

{{ dvf_js }}
{{ d3 }}
{{ vega }}
Expand All @@ -45,13 +49,21 @@
left:0;
}

{% for name, plugin in plugins.items() %}
{{plugin.render_css()}}
{% endfor %}

</style>
</head>

<body>

<div class="folium-map" id="{{ map_id }}" {{ size }}></div>

{% for name, plugin in plugins.items() %}
{{plugin.render_html()}}
{% endfor %}

<script>

{{ vega_parse }}
Expand Down Expand Up @@ -151,6 +163,10 @@

{% if fit_bounds %}{{ fit_bounds }}{% endif %}

{% for name, plugin in plugins.items() %}
{{plugin.render_js()}}
{% endfor %}

</script>

</body>
5 changes: 4 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ def walk_subpkg(name):
'templates/*.html',
'templates/*.js',
'templates/*.txt'] + walk_subpkg('templates/tiles')}
pkgs = ['folium',
'folium.plugins',
]

LICENSE = read('LICENSE.txt')
version = find_version('folium', '__init__.py')
Expand All @@ -62,7 +65,7 @@ def walk_subpkg(name):
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'License :: OSI Approved :: MIT License'],
packages=['folium'],
packages=pkgs,
package_data=pkg_data,
zip_safe=False)

Expand Down
19 changes: 18 additions & 1 deletion tests/folium_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import vincent
import folium
from folium.six import PY3
from folium.plugins import ScrollZoomToggler, MarkerCluster


def setup_data():
Expand Down Expand Up @@ -372,7 +373,7 @@ def test_map_build(self):
'max_lat': 90,
'min_lon': -180,
'max_lon': 180}
HTML = html_templ.render(tmpl)
HTML = html_templ.render(tmpl, plugins={})

assert self.map.HTML == HTML

Expand Down Expand Up @@ -483,3 +484,19 @@ def test_fit_bounds(self):
self.map.fit_bounds(bounds, max_zoom=15, padding=(3, 3))
assert self.map.template_vars['fit_bounds'] == fit_bounds_rendered

def test_scroll_zoom_toggler_plugin(self):
"test ScrollZoomToggler plugin"""
a_map = folium.Map([45,3], zoom_start=4)
a_map.add_plugin(ScrollZoomToggler(False))
a_map._build_map()

def test_marker_cluster_plugin(self):
"test MarkerCluster plugin"""
data = [(35,-12,"lower left"),
(35, 30,"lower right"),
(60,-12,"upper left"),
(60, 30,"upper right"),
]
a_map = folium.Map([0,0], zoom_start=0)
a_map.add_plugin(MarkerCluster(data))
a_map._build_map()