Cluster Markers
Learn how to cluster a group of markers together into a single marker cluster.
We'll cover the following
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
npm install @googlemaps/markerclusterer
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 });
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:
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.