Skip to content

Add a script version of MarkerCluster to speedup creating many markers.  #416

Description

@ruoyu0088

For example following code costs 5 seconds to add 1000 markers:

import folium
import numpy as np
from folium.plugins import MarkerCluster
N = 1000
fig = folium.element.Figure()
map_ = folium.Map(location=[20, 50], zoom_start=3)
cluster = MarkerCluster(np.random.uniform(0, 90, (N, 2))).add_to(map_)
map_.add_to(fig)

and the output html contains code for 1000 markers.

I tried a Javascript version to speedup this:

class MarkerClusterScript(MarkerCluster):
    def __init__(self, data, callback):
        from jinja2 import Template
        super(MarkerClusterScript, self).__init__([])
        self._name = 'Script'
        self._data = data
        if callable(callback):
            from flexx.pyscript import py2js
            self._callback =  py2js(callback, new_name="callback")
        else:
            self._callback = "var callback = {};".format(_callback)

        self._template = Template(u"""
{% macro script(this, kwargs) %}
(function(){
    var data = {{this._data}};
    var map = {{this._parent.get_name()}};
    var cluster = L.markerClusterGroup();
    {{this._callback}}

    for (var i = 0; i < data.length; i++) {
        var row = data[i];
        var marker = callback(row);
        marker.addTo(cluster);
    }

    cluster.addTo(map);
})();
{% endmacro %}
            """)

and then create the map by

import pandas as pd
N = 1000
df = pd.DataFrame(np.random.uniform(0, 90, (N, 2)), columns=list("xy"))
df["color"] = np.random.choice(["red", "green", "blue"], N)

fig = folium.element.Figure()
map_ = folium.Map(location=[20, 50], zoom_start=3)

def create_marker(row):
    icon = L.AwesomeMarkers.icon({markerColor: row.color})    
    marker = L.marker(L.LatLng(row.x, row.y))
    marker.setIcon(icon)
    return marker

MarkerClusterScript(df.to_json(orient="records"), callback=create_marker).add_to(map_)
map_.add_to(fig)

It only takes 0.3 seconds. All the data are saved in a javascript array, and the for-loop for creating markers occured in web brower.

I suggest to add this kind of Classes for speedup.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions