|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Marker Cluster plugin |
| 4 | +--------------------- |
| 5 | +
|
| 6 | +Creates a MarkerCluster plugin to add on a folium map. |
| 7 | +""" |
| 8 | + |
| 9 | +from jinja2 import Template |
| 10 | + |
| 11 | +from folium.plugins.marker_cluster import MarkerCluster |
| 12 | + |
| 13 | + |
| 14 | +class FastMarkerCluster(MarkerCluster): |
| 15 | + """Add marker clusters to a map using in-browser rendering""" |
| 16 | + def __init__(self, data, callback=None): |
| 17 | + """Add marker clusters to a map using in-browser rendering. |
| 18 | + Using FastMarkerCluster it is possible to render 000's of |
| 19 | + points far quicker than the MarkerCluster class. |
| 20 | +
|
| 21 | + Be aware that the FastMarkerCluster class passes an empty |
| 22 | + list to the parent class' __init__ method during initialisation. |
| 23 | + This means that the add_child method is never called, and |
| 24 | + no reference to any marker data are retained. Methods such |
| 25 | + as get_bounds() are therefore not available when using it. |
| 26 | +
|
| 27 | + Parameters |
| 28 | + ---------- |
| 29 | + data: list |
| 30 | + List of list of shape [[], []]. Data points should be of |
| 31 | + the form [[lat, lng]]. |
| 32 | +
|
| 33 | + callback: string, default None |
| 34 | + A string representation of a valid Javascript function |
| 35 | + that will be passed a lat, lon coordinate pair. See the |
| 36 | + FasterMarkerCluster for an example of a custom callback. |
| 37 | +
|
| 38 | + """ |
| 39 | + super(FastMarkerCluster, self).__init__([]) |
| 40 | + self._name = 'FastMarkerCluster' |
| 41 | + self._data = data |
| 42 | + |
| 43 | + if callback is None: |
| 44 | + self._callback = ('var callback;\n' + |
| 45 | + 'callback = function (row) {\n' + |
| 46 | + '\tvar icon, marker;\n' + |
| 47 | + '\t// Returns a L.marker object\n' + |
| 48 | + '\ticon = L.AwesomeMarkers.icon();\n' + |
| 49 | + '\tmarker = L.marker(new L.LatLng(row[0], ' + |
| 50 | + 'row[1]));\n' + |
| 51 | + '\tmarker.setIcon(icon);\n' + |
| 52 | + '\treturn marker;\n' + |
| 53 | + '};') |
| 54 | + else: |
| 55 | + self._callback = "var callback = {};".format(callback) |
| 56 | + |
| 57 | + self._template = Template(u""" |
| 58 | + {% macro script(this, kwargs) %} |
| 59 | + {{this._callback}} |
| 60 | +
|
| 61 | + (function(){ |
| 62 | + var data = {{this._data}}; |
| 63 | + var map = {{this._parent.get_name()}}; |
| 64 | + var cluster = L.markerClusterGroup(); |
| 65 | +
|
| 66 | + for (var i = 0; i < data.length; i++) { |
| 67 | + var row = data[i]; |
| 68 | + var marker = callback(row); |
| 69 | + marker.addTo(cluster); |
| 70 | + } |
| 71 | +
|
| 72 | + cluster.addTo(map); |
| 73 | + })(); |
| 74 | + {% endmacro %}""") |
0 commit comments