@128keaton/leaflet.markercluster 中文文档教程

发布于 5年前 浏览 29 项目主页 更新于 3年前

Leaflet.markercluster

Leaflet 提供漂亮的动画标记聚类功能,这是一个用于交互式地图的 JS 库。

需要 Leaflet 1.0.0

cluster map example

对于 Leaflet 0.7 兼容版本,使用 leaflet-0.7 分支
对于 Leaflet 0.5 兼容版本,下载 b128e950
对于 Leaflet 0.4 兼容版本,下载 0.2 版本

Table of Contents

Using the plugin

将插件 CSS 和 JS 文件包含在您的在 Leaflet 文件之后的页面,使用您选择的方法:

  • 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

在每种情况下,使用 dist 文件夹中的文件:

  • 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

安装 jake npm install -g jake 然后运行 ​​npm install

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

Examples

请参阅包含的示例以了解用法。

realworld example 是一个很好的起点,它使用了所有聚类器的默认值。 或者查看自定义示例,了解如何自定义clusterer

Usage

创建一个新的 MarkerClusterGroup,将标记添加到其中,然后将其添加到地图

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

Options

Defaults

默认情况下,Clusterer 为您启用了一些不错的默认设置:

  • 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 }.

您可以在创建 MarkerClusterGroup 时根据需要在选项中禁用其中任何一个:

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

Customising the Clustered Markers

作为一个选项对于 MarkerClusterGroup,您可以提供自己的功能来为集群标记创建图标。 默认实现在 10 和 100 的范围内更改颜色,但更高级的用途可能需要对此进行自定义。 如果你这样做,你不需要包含 .Default css。 系统向您传递了一个 MarkerCluster 对象,您可能希望使用 getChildCount()getAllChildMarkers() 来计算要显示的图标。

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

请查看自定义示例以获取相关示例。

如果您需要更新簇图标(例如它们基于标记实时数据),请使用方法refreshClusters()

Customising Spiderfy shape positions

您还可以提供自定义函数作为 MarkerClusterGroup 的选项以覆盖 spiderfy 形状位置。 下面的示例实现了覆盖默认圆形的线性 spiderfy 位置。

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

addLayers 方法的选项。 有关分块工作原理的说明,请参阅#357

  • 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

clickmouseover 等传单事件仅与集群中的标记 相关。 要接收集群事件,请收听 'cluster' + '',例如:clusterclickclustermouseoverclustermouseout 。

按如下方式设置回调以处理这两种情况:

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

支持 addLayerremoveLayerclearLayers,它们应该适用于大多数用途。

Bulk adding and removing Markers

addLayersremoveLayers 是用于添加和删除标记的批量方法,在批量添加/删除标记时应优于单一版本。 每个都有一个标记数组。 您可以使用专用选项 微调addLayers 的行为。

这些方法从层组类型中提取非组层子层,甚至是深度嵌套的。 但是,请注意:

  • 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.

如果您要删除大量标记,那么调用 clearLayers 然后调用 addLayers 来添加您不想删除的标记。有关详细信息,请参阅#59

Getting the visible parent of a marker

如果您的 MarkerClusterGroup 中有一个标记,并且您想要获取它的可见父级(它本身或它包含在当前在地图上可见的集群中)。 如果标记及其父集群当前不可见(它们不在可见视点附近),这将返回 null

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

Refreshing the clusters icon

如果您有自定义集群图标要使用包含的标记中的一些数据,并且稍后该数据发生变化,请使用此方法强制刷新群集图标。 您可以使用方法:

  • 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);

该插件还在 L.Marker 上添加了一个方法,可以轻松更新底层图标选项并刷新图标。 如果传递计算结果为 true 的第二个参数,该方法还将在该单个标记的父 MarkerClusterGroup 上触发 refreshCluster

// 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

以下方法可用于群集(不是组)。 它们通常用于事件处理。

Getting the bounds of a cluster

当您从集群接收到事件时,您可以查询它的范围。

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

您还可以查询边界凸多边形。 有关工作示例,请参阅 example/marker-clustering-convexhull.html

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

Zooming to the bounds of a cluster

当您收到来自集群的事件时,您可以通过一个简单的步骤缩放到它的边界。 如果所有标记都将出现在更高的缩放级别,则缩放级别将改为缩放到。 zoomToBounds 采用可选参数将选项传递给生成的fitBounds 调用< /a>。

有关工作示例,请参阅 marker-clustering-zoomtobounds.html

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

Clusterer 可以处理 10,000 甚至 50,000 个标记(在 chrome 中)。 IE9 在 50,000 时有一些问题。

注意:这两个示例使用设置为 true 的 chunkedLoading 选项,以避免长时间锁定浏览器。

License

Leaflet.markercluster 是免费软件,可以在 MIT-LICENSE 下重新分发。

Build Status

Sub-plugins

Leaflet.markercluster 插件非常流行,因此它产生高和 对增加功能的不同期望。

如果您是这种情况,请务必先查看存储库 问题以防万一 您正在寻找的问题已经得到讨论,并且会提出一些解决方法。

还要检查以下子插件:

PluginDescriptionMaintainer
Leaflet.FeatureGroup.SubGroupCreates 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.LayerSupportBrings 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.FreezableAdds 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.PlacementStrategiesImplements new strategies to position clustered markers (eg: clock, concentric circles, …). Recommended to use with circleMarkers. Demoadammertel / UNIVIE
Leaflet.MarkerCluster.ListDisplays child elements in a list. Suitable for mobile devices. Demoadammertel / UNIVIE

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:

PluginDescriptionMaintainer
Leaflet.FeatureGroup.SubGroupCreates 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.LayerSupportBrings 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.FreezableAdds 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.PlacementStrategiesImplements new strategies to position clustered markers (eg: clock, concentric circles, …). Recommended to use with circleMarkers. Demoadammertel / UNIVIE
Leaflet.MarkerCluster.ListDisplays child elements in a list. Suitable for mobile devices. Demoadammertel / UNIVIE
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文