Cluster Markers

Learn how to cluster a group of markers together into a single marker cluster.

Marker clusters

Sometimes, it becomes incredibly messy when using a large number of markers, especially when zooming out on a map. To counter this issue, we can use the marker clusters to display many markers from a particular region concentrated in one place on the map. Then, as the cluster region is zoomed in on, the individual markers can be seen.

Google’s markerclusterer library

Use the googlemaps/markerclusterer library in combination with Maps JS API to cluster our markers. That’s the easiest way to detect markers and combine those that are close to each other into marker clusters.

We can use the following commands to add the markerclusterer library to the system with NPMNode package manager is the world’s largest Software Library. It is a software Package Manager and Installer. It is also used to share software. or CDNContent delivery networks are file hosting services of common libraries.:

npm install @googlemaps/markerclusterer
Install marker clusterer

After the markerclusterer library is installed, it can be used inside the web application, depending on the installation. Here’s a code snippet that illustrates how the library is used in the index.js file:

import { MarkerClusterer } from "@googlemaps/markerclusterer";
const markerCluster = new MarkerClusterer({ map, markers });
Import marker clusterer

For more details regarding this library, refer to this documentation.

Code example

Use the CDN method to install the markerclusterer library, as seen in line 11 of the HTML file. Here’s an example of a map in which marker clusters are used:

Cluster markers

Here’s a brief explanation of the JavaScript file in the above code widget:

  • Line 8: We initialize a string of initials used as labels for markers.
  • Lines 11–18: We map the array of location coordinates into an array of Marker objects.
  • Line 21: We use the MarkerClusterer method to cluster and manage the list of created markers.
  • Line 25: We define the locations array that holds the list of coordinates for the created markers.