Clustering | 2GIS Documentation

Clustering

The marker clustering helps you to manage multiple markers at different zoom levels. When a user views the map at a high zoom level, the individual markers show on the map. When the user zooms out, the markers gather together into clusters, to make viewing the map easier. If you have a lot of markers on the map, it’s better to use a clustering to organize them better visually.

To add marker clustering functionality to the Map you need to include the clustering plugin JS file after MapGL API file using unpkg CDN:

<script src="https://unpkg.com/@2gis/mapgl-clusterer@^1/dist/clustering.js"></script>

Or using NPM:

npm install @2gis/mapgl-clusterer

First you need to instantiate the Clusterer.

If you install the clustering plugin using NPM, you can import the Clusterer to your project as shown below:

// import 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,
});

If you use unpkg CDN, you need to instantiate the Clusterer via the global object mapgl:

const clusterer = new mapgl.Clusterer(map, {
    radius: 60,
});

The first argument of the Clusterer constructor is an instance of the Map, the second - ClustererOptions.

The clusterer is ready to go. The next step will be markers loading. To add markers to the clusterer you need to use the load method. As an argument this method takes an array of InputMarker markers.

In the example below the markers will be added to the clusterer with default styles:

const markers = [
    { coordinates: [55.27887, 25.21001] },
    { coordinates: [55.30771, 25.20314] },
    { coordinates: [55.35266, 25.24382] },
    ...
];

clusterer.load(markers);

The markers passed to the clusterer will display on the map: