Skip to content

Instantly share code, notes, and snippets.

@vgrem
Created July 9, 2019 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vgrem/b72b9a17357d1bd1f4da3757ed755635 to your computer and use it in GitHub Desktop.
Save vgrem/b72b9a17357d1bd1f4da3757ed755635 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
#%%
import json
import folium
from folium import Marker
from folium.plugins import MarkerCluster
from jinja2 import Template
class MarkerWithProps(Marker):
_template = Template(u"""
{% macro script(this, kwargs) %}
var {{this.get_name()}} = L.marker(
[{{this.location[0]}}, {{this.location[1]}}],
{
icon: new L.Icon.Default(),
{%- if this.draggable %}
draggable: true,
autoPan: true,
{%- endif %}
{%- if this.props %}
props : {{ this.props }}
{%- endif %}
}
)
.addTo({{this._parent.get_name()}});
{% endmacro %}
""")
def __init__(self, location, popup=None, tooltip=None, icon=None,
draggable=False, props = None ):
super(MarkerWithProps, self).__init__(location=location,popup=popup,tooltip=tooltip,icon=icon,draggable=draggable)
self.props = json.loads(json.dumps(props))
map = folium.Map(location=[44, -73], zoom_start=4)
marker_data =(
{
'location':[40.67, -73.94],
'population': 200
},
{
'location':[44.67, -73.94],
'population': 300
}
)
icon_create_function = '''
function(cluster) {
var markers = cluster.getAllChildMarkers();
var sum = 0;
for (var i = 0; i < markers.length; i++) {
sum += markers[i].options.props.population;
}
var avg = sum/cluster.getChildCount();
return L.divIcon({
html: '<b>' + avg + '</b>',
className: 'marker-cluster marker-cluster-small',
iconSize: new L.Point(20, 20)
});
}
'''
marker_cluster = MarkerCluster(icon_create_function=icon_create_function)
for marker_item in marker_data:
marker = MarkerWithProps(
location=marker_item['location'],
props = { 'population': marker_item['population']}
)
marker.add_to(marker_cluster)
marker_cluster.add_to(map)
#m.save(os.path.join('results', '1000_MarkerCluster0.html'))
map
#%%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment