Marker clustering
If you have a large number of markers concentrated in one area, you can use marker clustering to combine them into a single object when the map is zoomed out to reduce the visual clutter.
To use marker clustering, you need to include the clustering plugin in your project. To do this, add the following line after the main MapGL script:
<script src="https://unpkg.com/@2gis/mapgl-clusterer@^2/dist/clustering.js"></script>
Or you can install the needed package using npm:
npm install @2gis/mapgl-clusterer
Usage
To create a cluster, first you need to initialize the Clusterer object:
const clusterer = new mapgl.Clusterer(map, {
radius: 60,
});
Or, if you are using npm:
// Import either as an ES module...
import { Clusterer } from '@2gis/mapgl-clusterer';
// ...or as a CommonJS module
const { Clusterer } = require('@2gis/mapgl-clusterer');
const clusterer = new Clusterer(map, {
radius: 60,
});
The radius
parameter is a distance in pixels. If the distance between markers is less than this value, the markers will be merged into a single object.
Once the cluster is initialized, the next step is to add markers to it. You do not need to create marker objects explicitly. Instead, you need to call the load()
method and pass an array of marker options (InputMarker). For example, to create a cluster of three markers, you can use code similar to this:
const markers = [
{ coordinates: [55.27887, 25.21001] },
{ coordinates: [55.30771, 25.20314] },
{ coordinates: [55.35266, 25.24382] },
];
clusterer.load(markers);