Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

leaflet.markercluster

Leaflet1.1mMIT1.5.3TypeScript support: definitely-typed

Provides Beautiful Animated Marker Clustering functionality for Leaflet

gis, map, cluster

readme

Leaflet.markercluster

Provides Beautiful Animated Marker Clustering functionality for Leaflet, a JS library for interactive maps.

Requires Leaflet 1.0.0

cluster map example

For a Leaflet 0.7 compatible version, use the leaflet-0.7 branch
For a Leaflet 0.5 compatible version, Download b128e950
For a Leaflet 0.4 compatible version, Download the 0.2 release

Table of Contents

Using the plugin

Include the plugin CSS and JS files on your page after Leaflet files, using your method of choice:

  • Download the v1.4.1 release
  • Use unpkg CDN: https://unpkg.com/leaflet.markercluster@1.4.1/dist/
  • Install with npm: npm install leaflet.markercluster

In each case, use files in the dist folder:

  • MarkerCluster.css
  • MarkerCluster.Default.css (not needed if you use your own iconCreateFunction instead of the default one)
  • leaflet.markercluster.js (or leaflet.markercluster-src.js for the non-minified version)

Building, testing and linting scripts

Install jake npm install -g jake then run npm install

  • To check the code for errors and build Leaflet from source, run jake.
  • To run the tests, run jake test.

Examples

See the included examples for usage.

The realworld example is a good place to start, it uses all of the defaults of the clusterer. Or check out the custom example for how to customise the behaviour and appearance of the clusterer

Usage

Create a new MarkerClusterGroup, add your markers to it, then add it to the map

var markers = L.markerClusterGroup();
markers.addLayer(L.marker(getRandomLatLng(map)));
... Add more layers ...
map.addLayer(markers);

Options

Defaults

By default the Clusterer enables some nice defaults for you:

  • showCoverageOnHover: When you mouse over a cluster it shows the bounds of its markers.
  • zoomToBoundsOnClick: When you click a cluster we zoom to its bounds.
  • spiderfyOnMaxZoom: When you click a cluster at the bottom zoom level we spiderfy it so you can see all of its markers. (Note: the spiderfy occurs at the current zoom level if all items within the cluster are still clustered at the maximum zoom level or at zoom specified by disableClusteringAtZoom option)
  • removeOutsideVisibleBounds: Clusters and markers too far from the viewport are removed from the map for performance.
  • spiderLegPolylineOptions: Allows you to specify PolylineOptions to style spider legs. By default, they are { weight: 1.5, color: '#222', opacity: 0.5 }.

You can disable any of these as you want in the options when you create the MarkerClusterGroup:

var markers = L.markerClusterGroup({
    spiderfyOnMaxZoom: false,
    showCoverageOnHover: false,
    zoomToBoundsOnClick: false
});

Customising the Clustered Markers

As an option to MarkerClusterGroup you can provide your own function for creating the Icon for the clustered markers. The default implementation changes color at bounds of 10 and 100, but more advanced uses may require customising this. You do not need to include the .Default css if you go this way. You are passed a MarkerCluster object, you'll probably want to use getChildCount() or getAllChildMarkers() to work out the icon to show.

var markers = L.markerClusterGroup({
    iconCreateFunction: function(cluster) {
        return L.divIcon({ html: '<b>' + cluster.getChildCount() + '</b>' });
    }
});

Check out the custom example for an example of this.

If you need to update the clusters icon (e.g. they are based on markers real-time data), use the method refreshClusters().

Customising Spiderfy shape positions

You can also provide a custom function as an option to MarkerClusterGroup to override the spiderfy shape positions. The example below implements linear spiderfy positions which overrides the default circular shape.

var markers = L.markerClusterGroup({
    spiderfyShapePositions: function(count, centerPt) {
                var distanceFromCenter = 35,
                    markerDistance = 45,
                    lineLength = markerDistance * (count - 1),
                    lineStart = centerPt.y - lineLength / 2,
                    res = [],
                    i;

                res.length = count;

                for (i = count - 1; i >= 0; i--) {
                    res[i] = new Point(centerPt.x + distanceFromCenter, lineStart + markerDistance * i);
                }

                return res;
            }
});

All Options

Enabled by default (boolean options)

  • showCoverageOnHover: When you mouse over a cluster it shows the bounds of its markers.
  • zoomToBoundsOnClick: When you click a cluster we zoom to its bounds.
  • spiderfyOnMaxZoom: When you click a cluster at the bottom zoom level we spiderfy it so you can see all of its markers. (Note: the spiderfy occurs at the current zoom level if all items within the cluster are still clustered at the maximum zoom level or at zoom specified by disableClusteringAtZoom option).
  • removeOutsideVisibleBounds: Clusters and markers too far from the viewport are removed from the map for performance.
  • animate: Smoothly split / merge cluster children when zooming and spiderfying. If L.DomUtil.TRANSITION is false, this option has no effect (no animation is possible).

Other options

  • animateAddingMarkers: If set to true (and animate option is also true) then adding individual markers to the MarkerClusterGroup after it has been added to the map will add the marker and animate it into the cluster. Defaults to false as this gives better performance when bulk adding markers. addLayers does not support this, only addLayer with individual Markers.
  • disableClusteringAtZoom: If set, at this zoom level and below, markers will not be clustered. This defaults to disabled. See Example. Note: you may be interested in disabling spiderfyOnMaxZoom option when using disableClusteringAtZoom.
  • maxClusterRadius: The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. Decreasing will make more, smaller clusters. You can also use a function that accepts the current map zoom and returns the maximum cluster radius in pixels.
  • polygonOptions: Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster. Defaults to empty, which lets Leaflet use the default Path options.
  • singleMarkerMode: If set to true, overrides the icon for all added markers to make them appear as a 1 size cluster. Note: the markers are not replaced by cluster objects, only their icon is replaced. Hence they still react to normal events, and option disableClusteringAtZoom does not restore their previous icon (see #391).
  • spiderLegPolylineOptions: Allows you to specify PolylineOptions to style spider legs. By default, they are { weight: 1.5, color: '#222', opacity: 0.5 }.
  • spiderfyDistanceMultiplier: Increase from 1 to increase the distance away from the center that spiderfied markers are placed. Use if you are using big marker icons (Default: 1).
  • iconCreateFunction: Function used to create the cluster icon. See the default implementation or the custom example.
  • spiderfyShapePositions: Function used to override spiderfy default shape positions.
  • clusterPane: Map pane where the cluster icons will be added. Defaults to L.Marker's default (currently 'markerPane'). See the pane example.

Chunked addLayers options

Options for the addLayers method. See #357 for explanation on how the chunking works.

  • chunkedLoading: Boolean to split the addLayers processing in to small intervals so that the page does not freeze.
  • chunkInterval: Time interval (in ms) during which addLayers works before pausing to let the rest of the page process. In particular, this prevents the page from freezing while adding a lot of markers. Defaults to 200ms.
  • chunkDelay: Time delay (in ms) between consecutive periods of processing for addLayers. Default to 50ms.
  • chunkProgress: Callback function that is called at the end of each chunkInterval. Typically used to implement a progress indicator, e.g. code in RealWorld 50k. Defaults to null. Arguments:
    1. Number of processed markers
    2. Total number of markers being added
    3. Elapsed time (in ms)

Events

Leaflet events like click, mouseover, etc. are just related to Markers in the cluster. To receive events for clusters, listen to 'cluster' + '<eventName>', ex: clusterclick, clustermouseover, clustermouseout.

Set your callback up as follows to handle both cases:

markers.on('click', function (a) {
    console.log('marker ' + a.layer);
});

markers.on('clusterclick', function (a) {
    // a.layer is actually a cluster
    console.log('cluster ' + a.layer.getAllChildMarkers().length);
});

Additional MarkerClusterGroup Events

  • animationend: Fires when marker clustering/unclustering animation has completed
  • spiderfied: Fires when overlapping markers get spiderified (Contains cluster and markers attributes)
  • unspiderfied: Fires when overlapping markers get unspiderified (Contains cluster and markers attributes)

Methods

Group methods

Adding and removing Markers

addLayer, removeLayer and clearLayers are supported and they should work for most uses.

Bulk adding and removing Markers

addLayers and removeLayers are bulk methods for adding and removing markers and should be favoured over the single versions when doing bulk addition/removal of markers. Each takes an array of markers. You can use dedicated options to fine-tune the behaviour of addLayers.

These methods extract non-group layer children from Layer Group types, even deeply nested. However, be noted that:

  • chunkProgress jumps backward when addLayers finds a group (since appending its children to the input array makes the total increase).
  • Groups are not actually added into the MarkerClusterGroup, only their non-group child layers. Therfore, hasLayer method will return true for non-group child layers, but false on any (possibly parent) Layer Group types.

If you are removing a lot of markers it will almost definitely be better to call clearLayers then call addLayers to add the markers you don't want to remove back in. See #59 for details.

Getting the visible parent of a marker

If you have a marker in your MarkerClusterGroup and you want to get the visible parent of it (Either itself or a cluster it is contained in that is currently visible on the map). This will return null if the marker and its parent clusters are not visible currently (they are not near the visible viewpoint)

var visibleOne = markerClusterGroup.getVisibleParent(myMarker);
console.log(visibleOne.getLatLng());

Refreshing the clusters icon

If you have customized the clusters icon to use some data from the contained markers, and later that data changes, use this method to force a refresh of the cluster icons. You can use the method:

  • without arguments to force all cluster icons in the Marker Cluster Group to be re-drawn.
  • with an array or a mapping of markers to force only their parent clusters to be re-drawn.
  • with an L.LayerGroup. The method will look for all markers in it. Make sure it contains only markers which are also within this Marker Cluster Group.
  • with a single marker.
    markers.refreshClusters();
    markers.refreshClusters([myMarker0, myMarker33]);
    markers.refreshClusters({id_0: myMarker0, id_any: myMarker33});
    markers.refreshClusters(myLayerGroup);
    markers.refreshClusters(myMarker);

The plugin also adds a method on L.Marker to easily update the underlying icon options and refresh the icon. If passing a second argument that evaluates to true, the method will also trigger a refreshCluster on the parent MarkerClusterGroup for that single marker.

// Use as many times as required to update markers,
// then call refreshClusters once finished.
for (i in markersSubArray) {
    markersSubArray[i].refreshIconOptions(newOptionsMappingArray[i]);
}
markers.refreshClusters(markersSubArray);

// If updating only one marker, pass true to
// refresh this marker's parent clusters right away.
myMarker.refreshIconOptions(optionsMap, true); 

Other Group Methods

  • hasLayer(layer): Returns true if the given layer (marker) is in the MarkerClusterGroup.
  • zoomToShowLayer(layer, callback): Zooms to show the given marker (spiderfying if required), calls the callback when the marker is visible on the map.

Clusters methods

The following methods can be used with clusters (not the group). They are typically used for event handling.

Getting the bounds of a cluster

When you receive an event from a cluster you can query it for the bounds.

markers.on('clusterclick', function (a) {
    var latLngBounds = a.layer.getBounds();
});

You can also query for the bounding convex polygon. See example/marker-clustering-convexhull.html for a working example.

markers.on('clusterclick', function (a) {
    map.addLayer(L.polygon(a.layer.getConvexHull()));
});

Zooming to the bounds of a cluster

When you receive an event from a cluster you can zoom to its bounds in one easy step. If all of the markers will appear at a higher zoom level, that zoom level is zoomed to instead. zoomToBounds takes an optional argument to pass options to the resulting fitBounds call.

See marker-clustering-zoomtobounds.html for a working example.

markers.on('clusterclick', function (a) {
    a.layer.zoomToBounds({padding: [20, 20]});
});

Other clusters methods

  • getChildCount: Returns the total number of markers contained within that cluster.
  • getAllChildMarkers(storage: array | undefined, ignoreDraggedMarker: boolean | undefined): Returns an array of all markers contained within this cluster (storage will be used if provided). If ignoreDraggedMarker is true and there is currently a marker dragged, the dragged marker will not be included in the array.
  • spiderfy: Spiderfies the child markers of this cluster
  • unspiderfy: Unspiderfies a cluster (opposite of spiderfy)

Handling LOTS of markers

The Clusterer can handle 10,000 or even 50,000 markers (in chrome). IE9 has some issues with 50,000.

Note: these two examples use the chunkedLoading option set to true in order to avoid locking the browser for a long time.

License

Leaflet.markercluster is free software, and may be redistributed under the MIT-LICENSE.

Build Status

Sub-plugins

Leaflet.markercluster plugin is very popular and as such it generates high and diverse expectations for increased functionalities.

If you are in that case, be sure to have a look first at the repository issues in case what you are looking for would already be discussed, and some workarounds would be proposed.

Check also the below sub-plugins:

Plugin Description Maintainer
Leaflet.FeatureGroup.SubGroup Creates a Feature Group that adds its child layers into a parent group when added to a map (e.g. through L.Control.Layers). Typical usage is to dynamically add/remove groups of markers from Marker Cluster. ghybs
Leaflet.MarkerCluster.LayerSupport Brings compatibility with L.Control.Layers and other Leaflet plugins. I.e. everything that uses direct calls to map.addLayer and map.removeLayer. ghybs
Leaflet.MarkerCluster.Freezable Adds the ability to freeze clusters at a specified zoom. E.g. freezing at maxZoom + 1 makes as if clustering was programmatically disabled. ghybs
Leaflet.MarkerCluster.PlacementStrategies Implements new strategies to position clustered markers (eg: clock, concentric circles, ...). Recommended to use with circleMarkers. Demo adammertel / UNIVIE
Leaflet.MarkerCluster.List Displays child elements in a list. Suitable for mobile devices. Demo adammertel / UNIVIE

changelog

Leaflet.markercluster

(part of repo mgmt responsibilities transferred to @ykzeng)

1.5.3 (2021-10-18)

Bugfixes

  • Removing unnecessary files on npm package
  • Inlucding correct versioning on Github repo

1.5.2 (2021-10-18)

Improvements

Bugfixes

  • Fixed issue 907 and 967 with PR 1027 from DerGuteWolf
  • Removed unexpected dependencies in previous npm package

1.5.1 (2021-08-28)

Improvements

1.5.0 (2021-03-12)

Bugfixes

  • Updated peer dependency to match latest leaflet version (by @sanjpareek) #976

(all changes below without author notice were made by @danzel)

1.4.1 (2018-09-14)

Bugfixes

  • Better support stopping dragged markers from being clustered (by @DerGuteWolf) #909

1.4.0 (2018-08-22)

Required leaflet version bumped to 1.3.1

Improvements

  • Tests run against leaflet 1.1.0+ #863

Bugfixes

  • Fix clearLayers not removing removed markers #860
  • Remember opacity 0 correctly (by @r-yanyo) #890
  • Fix chunkedLoading LatLngBounds.intersects() (by @boldtrn) #743 #891

1.3.0 (2018-01-19)

Improvements

Bugfixes

  • Fix Spiderfier positioning for small markers (by @ghybs) #846
  • Fix anchor usage with latest leaflet version #861

1.2.0 (2017-11-06)

Improvements

  • Move clusterPane option in to options field (by @ghybs) #832

Bugfixes

1.1.0 (2017-08-27)

Improvements

  • Add clusterPane option to allow putting clusters in a different pane (by @ckrahe) #819

1.0.6 (2017-06-19)

Bugfixes

  • Fix some issues when used with non-integer zoom #789
  • Change examples to use https (by @ghybs) #794

1.0.5 (2017-04-26)

Improvements

  • Allow passing fitBounds options to zoomToBounds (by @timkelty) #779

Bugfixes

  • Fixed bug where disableClusteringAtZoom being 0 is treated the same as null (by @MrCheeze) #773

1.0.4 (2017-03-14)

Bugfixes

  • Fix errors removing a MarkerClusterGroup from the map during an animation #758

1.0.3 (2017-02-02)

Bugfixes

  • Fix moving markers while the MarkerClusterGroup is not on the map #753

1.0.2 (2017-01-27)

Improvements

  • Support layeradd and layerremove events #647

Bugfixes

  • Add support for maps with negative minZoom #704
  • Fixed zoomToShowLayer() markers disappearing bug (by @z3ut) #739
  • Fix an issue when opening a popup inside of zoomToShowLayer
  • If a marker is moved with an open popup on it, re-open the popup after moving it. #651

1.0.1 (2017-01-25)

Improvements

Bugfixes

1.0.0 (2016-10-03)

Improvements

Bugfixes

  • Fix getBounds when removeOutsideVisibleBounds: false is set. #321
  • Fix zoomToShowLayer fails after initial spiderfy #286
  • Fix cluster not disappearing on Android #344
  • Fix RemoveLayers() when spiderified (by @Grsmto) #358
  • Remove lines from map when removing cluster (by @olive380) #532
  • Fix getConvexHull when all markers are located at same latitude (by @olive380) #533
  • Fix removeLayers when cluster is not on the map (by @eschon) #556
  • Improved zoomToShowLayer with callback check (by @ghybs) #572
  • Improved reliability of RefreshSpec test suite for PhantomJS (by @ghybs) #577
  • Corrected effect of removeOutsideVisibleBounds option (by @ghybs) #575
  • Fix getLayer when provided a string #531
  • Documentation improvements (by @ghybs) #579
  • Correct _getExpandedVisibleBounds for Max Latitude (by @ghybs) #587
  • Correct unspiderfy vector (by @ghybs) #604
  • Remove "leaflet-cluster-anim" class on map remove while spiderfied (by @ghybs) #607
  • Fix disableClusteringAtZoom maxZoom troubles (by @OriginalSin) #609
  • Fix clusters not disappearing when they were near the edge on mobile (by @ghybs) #529
  • Remove leaflet from dependencies (by @ghybs) #639
  • Fix interaction between zoomOrSpiderfy and disableClusteringAtZoom (by @ghybs) #633 #648

0.4 (2013-12-19)

Improvements

  • Fix Quick Zoom in/out causing everything to disappear in Firefox (Reported by @paulovieira) #140
  • Slow the expand/contract animation down from 200ms to 300ms

Bugfixes

0.3 (2013-12-18)

Improvements

  • Work better with custom projections (by @andersarstrand) #74
  • Add custom getBounds that works (Reported by @2803media)
  • Allow spacing spiderfied icons further apart (Reported by @stevevance) #100
  • Add custom eachLayer that works (Reported by @cilogi) #102
  • Add an option (removeOutsideVisibleBounds) to prevent removing clusters that are outside of the visible bounds (by @wildhoney) #103
  • Add getBounds method to cluster (Reported by @nderambure) #88
  • Lots of unit tests
  • Support having Circle / CircleMarker as child markers
  • Add factory methods (Reported by @mourner) #21
  • Add getVisibleParent method to allow getting the visible parent cluster or the marker if it is visible. (By @littleiffel) #102
  • Allow adding non-clusterable things to a MarkerClusterGroup, we don't cluster them. (Reported by @benbalter) #195
  • removeLayer supports taking a FeatureGroup (Reported by @pabloalcaraz) #236
  • DistanceGrid tests, QuickHull tests and improvements (By @tmcw) #247 #248 #249
  • Implemented getLayers (Reported by @metajungle) #222
  • zoomToBounds now only zooms in as far as it needs to to get all of the markers on screen if this is less zoom than zooming to the actual bounds would be (Reported by @adamyonk) #185
  • Keyboard accessibility improvements (By @Zombienaute) #273
  • IE Specific css in the default styles is no longer a separate file (By @frankrowe) #280
  • Improve usability with small maps (Reported by @JSCSJSCS) #144
  • Implement FeatureGroup.getLayer (Reported by @newmanw) #244

Bugfixes

  • Fix singleMarkerMode when you aren't on the map (by @duncanparkes) #77
  • Fix clearLayers when you aren't on the map (by @duncanparkes) #79
  • IE10 Bug fix (Reported by @theLundquist) #86
  • Fixes for hasLayer after removing a layer (Reported by @cvisto) #44
  • Fix clearLayers not unsetting __parent of the markers, preventing them from being re-added. (Reported by @apuntovanini) #99
  • Fix map.removeLayer(markerClusterGroup) not working (Reported by @Driklyn) #108
  • Fix map.addLayers not updating cluster icons (Reported by @Driklyn) #114
  • Fix spiderfied clusters breaking if a marker is added to them (Reported by @Driklyn) #114
  • Don't show coverage for spiderfied clusters as it will be wrong. (Reported by @ajbeaven) #95
  • Improve zoom in/out immediately making all everything disappear, still issues in Firefox #140
  • Fix animation not stopping with only one marker. (Reported by @Driklyn) #146
  • Various fixes for new leaflet (Reported by @PeterAronZentai) #159
  • Fix clearLayers when we are spiderfying (Reported by @skullbooks) #162
  • Fix removing layers in certain situations (Reported by @bpavot) #160
  • Support calling hasLayer with null (by @l0c0luke) #170
  • Lots of fixes for removing a MarkerClusterGroup from the map (Reported by @annetdeboer) #200
  • Throw error when being added to a map with no maxZoom.
  • Fixes for markers not appearing after a big zoom (Reported by @arnoldbird) #216 (Reported by @mathilde-pellerin) #260
  • Fix coverage polygon not being removed when a MarkerClusterGroup is removed (Reported by @ZeusTheTrueGod) #245
  • Fix getVisibleParent when no parent is visible (Reported by @ajbeaven) #265
  • Fix spiderfied markers not hiding on a big zoom (Reported by @Vaesive) #268
  • Fix clusters not hiding on a big zoom (Reported by @versusvoid) #281
  • Don't fire multiple clustermouseover/off events due to child divs in the cluster marker (Reported by @heidemn) #252

0.2 (2012-10-11)

Improvements

  • Add addLayers/removeLayers bulk add and remove functions that perform better than the individual methods
  • Allow customising the polygon generated for showing the area a cluster covers (by @yohanboniface) #68
  • Add zoomToShowLayer method to zoom down to a marker then call a callback once it is visible
  • Add animateAddingMarkers to allow disabling animations caused when adding/removing markers
  • Add hasLayer
  • Pass the L.MarkerCluster to iconCreateFunction to give more flexibility deciding the icon
  • Make addLayers support geojson layers
  • Allow disabling clustering at a given zoom level
  • Allow styling markers that are added like they were clusters of size 1

Bugfixes

  • Support when leaflet is configured to use canvas rather than SVG
  • Fix some potential crashes in zoom handlers
  • Tidy up when we are removed from the map

0.1 (2012-08-16)

Initial Release!