UNPKG

20 kBMarkdownView Raw
1Leaflet.markercluster
2=====================
3
4Provides Beautiful Animated Marker Clustering functionality for [Leaflet](http://leafletjs.com), a JS library for interactive maps.
5
6*Requires Leaflet 1.0.0*
7
8![cluster map example](example/map.png)
9
10For a Leaflet 0.7 compatible version, [use the leaflet-0.7 branch](https://github.com/Leaflet/Leaflet.markercluster/tree/leaflet-0.7)<br>
11For a Leaflet 0.5 compatible version, [Download b128e950](https://github.com/Leaflet/Leaflet.markercluster/archive/b128e950d8f5d7da5b60bd0aa9a88f6d3dd17c98.zip)<br>
12For a Leaflet 0.4 compatible version, [Download the 0.2 release](https://github.com/Leaflet/Leaflet.markercluster/archive/0.2.zip)
13
14<!---
15TOC created with gh-md-toc
16https://github.com/ekalinin/github-markdown-toc
17removed link to h1 and indented back 2 spaces all links.
18-->
19## Table of Contents
20 * [Using the plugin](#using-the-plugin)
21 * [Building, testing and linting scripts](#building-testing-and-linting-scripts)
22 * [Examples](#examples)
23 * [Usage](#usage)
24 * [Options](#options)
25 * [Defaults](#defaults)
26 * [Customising the Clustered Markers](#customising-the-clustered-markers)
27 * [All Options](#all-options)
28 * [Enabled by default (boolean options)](#enabled-by-default-boolean-options)
29 * [Other options](#other-options)
30 * [Chunked addLayers options](#chunked-addlayers-options)
31 * [Events](#events)
32 * [Additional MarkerClusterGroup Events](#additional-markerclustergroup-events)
33 * [Methods](#methods)
34 * [Group methods](#group-methods)
35 * [Adding and removing Markers](#adding-and-removing-markers)
36 * [Bulk adding and removing Markers](#bulk-adding-and-removing-markers)
37 * [Getting the visible parent of a marker](#getting-the-visible-parent-of-a-marker)
38 * [Refreshing the clusters icon](#refreshing-the-clusters-icon)
39 * [Other Group Methods](#other-group-methods)
40 * [Clusters methods](#clusters-methods)
41 * [Getting the bounds of a cluster](#getting-the-bounds-of-a-cluster)
42 * [Zooming to the bounds of a cluster](#zooming-to-the-bounds-of-a-cluster)
43 * [Other clusters methods](#other-clusters-methods)
44 * [Handling LOTS of markers](#handling-lots-of-markers)
45 * [License](#license)
46 * [Sub-plugins](#sub-plugins)
47
48
49## Using the plugin
50Include the plugin CSS and JS files on your page after Leaflet files, using your method of choice:
51* [Download the `v1.4.1` release](https://github.com/Leaflet/Leaflet.markercluster/archive/v1.4.1.zip)
52* Use unpkg CDN: `https://unpkg.com/leaflet.markercluster@1.4.1/dist/`
53* Install with npm: `npm install leaflet.markercluster`
54
55In each case, use files in the `dist` folder:
56* `MarkerCluster.css`
57* `MarkerCluster.Default.css` (not needed if you use your own `iconCreateFunction` instead of the default one)
58* `leaflet.markercluster.js` (or `leaflet.markercluster-src.js` for the non-minified version)
59
60### Building, testing and linting scripts
61Install jake `npm install -g jake` then run `npm install`
62* To check the code for errors and build Leaflet from source, run `jake`.
63* To run the tests, run `jake test`.
64
65### Examples
66See the included examples for usage.
67
68The [realworld example](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-realworld.388.html) is a good place to start, it uses all of the defaults of the clusterer.
69Or check out the [custom example](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-custom.html) for how to customise the behaviour and appearance of the clusterer
70
71### Usage
72Create a new MarkerClusterGroup, add your markers to it, then add it to the map
73
74```javascript
75var markers = L.markerClusterGroup();
76markers.addLayer(L.marker(getRandomLatLng(map)));
77... Add more layers ...
78map.addLayer(markers);
79```
80
81## Options
82### Defaults
83By default the Clusterer enables some nice defaults for you:
84* **showCoverageOnHover**: When you mouse over a cluster it shows the bounds of its markers.
85* **zoomToBoundsOnClick**: When you click a cluster we zoom to its bounds.
86* **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*)
87* **removeOutsideVisibleBounds**: Clusters and markers too far from the viewport are removed from the map for performance.
88* **spiderLegPolylineOptions**: Allows you to specify [PolylineOptions](http://leafletjs.com/reference.html#polyline-options) to style spider legs. By default, they are `{ weight: 1.5, color: '#222', opacity: 0.5 }`.
89
90You can disable any of these as you want in the options when you create the MarkerClusterGroup:
91```javascript
92var markers = L.markerClusterGroup({
93 spiderfyOnMaxZoom: false,
94 showCoverageOnHover: false,
95 zoomToBoundsOnClick: false
96});
97```
98
99### Customising the Clustered Markers
100As an option to MarkerClusterGroup you can provide your own function for creating the Icon for the clustered markers.
101The default implementation changes color at bounds of 10 and 100, but more advanced uses may require customising this.
102You do not need to include the .Default css if you go this way.
103You are passed a MarkerCluster object, you'll probably want to use `getChildCount()` or `getAllChildMarkers()` to work out the icon to show.
104
105```javascript
106var markers = L.markerClusterGroup({
107 iconCreateFunction: function(cluster) {
108 return L.divIcon({ html: '<b>' + cluster.getChildCount() + '</b>' });
109 }
110});
111```
112Check out the [custom example](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-custom.html) for an example of this.
113
114If you need to update the clusters icon (e.g. they are based on markers real-time data), use the method [refreshClusters()](#refreshing-the-clusters-icon).
115
116### All Options
117#### Enabled by default (boolean options)
118* **showCoverageOnHover**: When you mouse over a cluster it shows the bounds of its markers.
119* **zoomToBoundsOnClick**: When you click a cluster we zoom to its bounds.
120* **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*).
121* **removeOutsideVisibleBounds**: Clusters and markers too far from the viewport are removed from the map for performance.
122* **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).
123
124#### Other options
125* **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.
126* **disableClusteringAtZoom**: If set, at this zoom level and below, markers will not be clustered. This defaults to disabled. [See Example](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-realworld-maxzoom.388.html). Note: you may be interested in disabling `spiderfyOnMaxZoom` option when using `disableClusteringAtZoom`.
127* **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.
128* **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](http://leafletjs.com/reference.html#path-options).
129* **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](https://github.com/Leaflet/Leaflet.markercluster/issues/391)).
130* **spiderLegPolylineOptions**: Allows you to specify [PolylineOptions](http://leafletjs.com/reference.html#polyline-options) to style spider legs. By default, they are `{ weight: 1.5, color: '#222', opacity: 0.5 }`.
131* **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).
132* **iconCreateFunction**: Function used to create the cluster icon. See [the default implementation](https://github.com/Leaflet/Leaflet.markercluster/blob/15ed12654acdc54a4521789c498e4603fe4bf781/src/MarkerClusterGroup.js#L542) or the [custom example](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-custom.html).
133* **clusterPane**: Map pane where the cluster icons will be added. Defaults to L.Marker's default (currently 'markerPane'). [See the pane example](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-pane.html).
134
135#### Chunked addLayers options
136Options for the [addLayers](#bulk-adding-and-removing-markers) method. See [#357](https://github.com/Leaflet/Leaflet.markercluster/issues/357) for explanation on how the chunking works.
137* **chunkedLoading**: Boolean to split the addLayer**s** processing in to small intervals so that the page does not freeze.
138* **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.
139* **chunkDelay**: Time delay (in ms) between consecutive periods of processing for addLayers. Default to 50ms.
140* **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](https://github.com/Leaflet/Leaflet.markercluster/blob/master/example/marker-clustering-realworld.50000.html#L33-L49). Defaults to null. Arguments:
141 1. Number of processed markers
142 2. Total number of markers being added
143 3. Elapsed time (in ms)
144
145## Events
146Leaflet events like `click`, `mouseover`, etc. are just related to _Markers_ in the cluster.
147To receive events for clusters, listen to `'cluster' + '<eventName>'`, ex: `clusterclick`, `clustermouseover`, `clustermouseout`.
148
149Set your callback up as follows to handle both cases:
150
151```javascript
152markers.on('click', function (a) {
153 console.log('marker ' + a.layer);
154});
155
156markers.on('clusterclick', function (a) {
157 // a.layer is actually a cluster
158 console.log('cluster ' + a.layer.getAllChildMarkers().length);
159});
160```
161
162### Additional MarkerClusterGroup Events
163
164- **animationend**: Fires when marker clustering/unclustering animation has completed
165- **spiderfied**: Fires when overlapping markers get spiderified (Contains ```cluster``` and ```markers``` attributes)
166- **unspiderfied**: Fires when overlapping markers get unspiderified (Contains ```cluster``` and ```markers``` attributes)
167
168## Methods
169
170### Group methods
171
172#### Adding and removing Markers
173`addLayer`, `removeLayer` and `clearLayers` are supported and they should work for most uses.
174
175#### Bulk adding and removing Markers
176`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](#chunked-addlayers-options) to fine-tune the behaviour of `addLayers`.
177
178These methods extract non-group layer children from Layer Group types, even deeply nested. _However_, be noted that:
179- `chunkProgress` jumps backward when `addLayers` finds a group (since appending its children to the input array makes the total increase).
180- 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.
181
182If 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](https://github.com/Leaflet/Leaflet.markercluster/issues/59#issuecomment-9320628) for details.
183
184#### Getting the visible parent of a marker
185If 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).
186This will return null if the marker and its parent clusters are not visible currently (they are not near the visible viewpoint)
187```javascript
188var visibleOne = markerClusterGroup.getVisibleParent(myMarker);
189console.log(visibleOne.getLatLng());
190```
191
192#### Refreshing the clusters icon
193If you have [customized](#customising-the-clustered-markers) 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.
194You can use the method:
195- without arguments to force all cluster icons in the Marker Cluster Group to be re-drawn.
196- with an array or a mapping of markers to force only their parent clusters to be re-drawn.
197- 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.
198- with a single marker.
199```javascript
200markers.refreshClusters();
201markers.refreshClusters([myMarker0, myMarker33]);
202markers.refreshClusters({id_0: myMarker0, id_any: myMarker33});
203markers.refreshClusters(myLayerGroup);
204markers.refreshClusters(myMarker);
205```
206
207The plugin also adds a method on L.Marker to easily update the underlying icon options and refresh the icon.
208If passing a second argument that evaluates to `true`, the method will also trigger a `refreshCluster` on the parent MarkerClusterGroup for that single marker.
209```javascript
210// Use as many times as required to update markers,
211// then call refreshClusters once finished.
212for (i in markersSubArray) {
213 markersSubArray[i].refreshIconOptions(newOptionsMappingArray[i]);
214}
215markers.refreshClusters(markersSubArray);
216
217// If updating only one marker, pass true to
218// refresh this marker's parent clusters right away.
219myMarker.refreshIconOptions(optionsMap, true);
220```
221
222#### Other Group Methods
223* **hasLayer**(layer): Returns true if the given layer (marker) is in the MarkerClusterGroup.
224* **zoomToShowLayer**(layer, callback): Zooms to show the given marker (spiderfying if required), calls the callback when the marker is visible on the map.
225
226### Clusters methods
227The following methods can be used with clusters (not the group). They are typically used for event handling.
228
229#### Getting the bounds of a cluster
230When you receive an event from a cluster you can query it for the bounds.
231```javascript
232markers.on('clusterclick', function (a) {
233 var latLngBounds = a.layer.getBounds();
234});
235```
236
237You can also query for the bounding convex polygon.
238See [example/marker-clustering-convexhull.html](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-convexhull.html) for a working example.
239```javascript
240markers.on('clusterclick', function (a) {
241 map.addLayer(L.polygon(a.layer.getConvexHull()));
242});
243```
244
245#### Zooming to the bounds of a cluster
246When you receive an event from a cluster you can zoom to its bounds in one easy step.
247If all of the markers will appear at a higher zoom level, that zoom level is zoomed to instead.
248`zoomToBounds` takes an optional argument to pass [options to the resulting `fitBounds` call](http://leafletjs.com/reference.html#map-fitboundsoptions).
249
250See [marker-clustering-zoomtobounds.html](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-zoomtobounds.html) for a working example.
251```javascript
252markers.on('clusterclick', function (a) {
253 a.layer.zoomToBounds({padding: [20, 20]});
254});
255```
256
257#### Other clusters methods
258* **getChildCount**: Returns the total number of markers contained within that cluster.
259* **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.
260* **spiderfy**: Spiderfies the child markers of this cluster
261* **unspiderfy**: Unspiderfies a cluster (opposite of spiderfy)
262
263## Handling LOTS of markers
264The Clusterer can handle 10,000 or even 50,000 markers (in chrome). IE9 has some issues with 50,000.
265- [realworld 10,000 example](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-realworld.10000.html)
266- [realworld 50,000 example](https://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-realworld.50000.html)
267
268Note: these two examples use the `chunkedLoading` option set to true in order to avoid locking the browser for a long time.
269
270## License
271
272Leaflet.markercluster is free software, and may be redistributed under the MIT-LICENSE.
273
274[![Build Status](https://travis-ci.org/Leaflet/Leaflet.markercluster.png?branch=master)](https://travis-ci.org/Leaflet/Leaflet.markercluster)
275
276## Sub-plugins
277Leaflet.markercluster plugin is very popular and as such it generates high and
278diverse expectations for increased functionalities.
279
280If you are in that case, be sure to have a look first at the repository
281[issues](https://github.com/Leaflet/Leaflet.markercluster/issues) in case what
282you are looking for would already be discussed, and some workarounds would be proposed.
283
284Check also the below sub-plugins:
285
286| Plugin | Description | Maintainer |
287| :----- | :---------- | :--------- |
288| [Leaflet.FeatureGroup.SubGroup](https://github.com/ghybs/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](https://github.com/ghybs) |
289| [Leaflet.MarkerCluster.LayerSupport](https://github.com/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](https://github.com/ghybs) |
290| [Leaflet.MarkerCluster.Freezable](https://github.com/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](https://github.com/ghybs) |
291| [Leaflet.MarkerCluster.PlacementStrategies](https://github.com/adammertel/Leaflet.MarkerCluster.PlacementStrategies) | Implements new strategies to position clustered markers (eg: clock, concentric circles, ...). Recommended to use with circleMarkers. [Demo](https://adammertel.github.io/Leaflet.MarkerCluster.PlacementStrategies/demo/demo1.html) | [adammertel](https://github.com/adammertel) / [UNIVIE](http://carto.univie.ac.at/) |
292| [Leaflet.MarkerCluster.List](https://github.com/adammertel/Leaflet.MarkerCluster.List) | Displays child elements in a list. Suitable for mobile devices. [Demo](https://adammertel.github.io/Leaflet.MarkerCluster.List/demo/demo1.html) | [adammertel](https://github.com/adammertel) / [UNIVIE](http://carto.univie.ac.at/) |