### Install project dependencies
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/CONTRIBUTING.md
Run this command to install all necessary dependencies for the project.
```bash
npm i
```
--------------------------------
### Complete Integration Example
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
A full implementation including map initialization, random marker generation, custom clustering options, and event listeners.
```html
```
--------------------------------
### Install MarkerClustererPlus via npm
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/README.md
Use npm to install the MarkerClustererPlus library. This is the recommended method for Node.js projects.
```bash
npm i @googlemaps/markerclustererplus
```
--------------------------------
### Initialize MarkerClusterer Instance
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Example showing how to instantiate the MarkerClusterer with a map, marker array, and configuration options.
```javascript
import MarkerClusterer from '@googlemaps/markerclustererplus';
// Initialize Google Map
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(37.4419, -122.1419),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create markers
const markers = [];
const locations = [
{ lat: 37.7749, lng: -122.4194 },
{ lat: 34.0522, lng: -118.2437 },
{ lat: 40.7128, lng: -74.0060 },
{ lat: 41.8781, lng: -87.6298 },
{ lat: 29.7604, lng: -95.3698 }
];
locations.forEach(location => {
const marker = new google.maps.Marker({
position: new google.maps.LatLng(location.lat, location.lng)
});
markers.push(marker);
});
// Create MarkerClusterer with options
const markerClusterer = new MarkerClusterer(map, markers, {
gridSize: 60, // Cluster grid size in pixels (default: 60)
maxZoom: 15, // Max zoom level for clustering (default: null)
minimumClusterSize: 2, // Min markers to form cluster (default: 2)
zoomOnClick: true, // Zoom when cluster clicked (default: true)
averageCenter: true, // Position cluster at average of markers (default: false)
ignoreHidden: false, // Ignore hidden markers (default: false)
title: 'Click to zoom' // Tooltip for clusters
});
```
--------------------------------
### Install MarkerClustererPlus via Package Managers
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Commands to install the library using npm or yarn, including TypeScript definitions.
```bash
# Install via npm
npm install @googlemaps/markerclustererplus
# Install via yarn
yarn add @googlemaps/markerclustererplus
# For TypeScript support
npm install -D @types/google.maps
```
--------------------------------
### Install MarkerClustererPlus via yarn
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/README.md
Use yarn to add the MarkerClustererPlus library to your project dependencies.
```bash
yarn add @googlemaps/markerclustererplus
```
--------------------------------
### Initialize MarkerClusterer
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/README.md
Import and initialize MarkerClusterer with a map instance and an array of markers. This is a basic setup for clustering.
```javascript
import MarkerClusterer from '@googlemaps/markerclustererplus';
const markerCluster = new MarkerClusterer(map, markers);
```
--------------------------------
### Install TypeScript Typings
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/README.md
Install the official TypeScript typings for Google Maps Platform to use with MarkerClustererPlus. Consider enabling `skipLibCheck` in your tsconfig.json.
```bash
npm i -D @types/google.maps
```
--------------------------------
### Run unit tests
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/CONTRIBUTING.md
Execute the project's unit test suite.
```bash
# Run unit tests.
npm test
```
--------------------------------
### Initialize MarkerClustererPlus Map
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/examples/speed_test_example.html
Sets up the map interface and initializes the clusterer on window load.
```javascript
google.maps.event.addDomListener(window, "load", speedTest.init);
```
--------------------------------
### Initialize MarkerClustererPlus with 100 markers
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/examples/simple_example.html
Sets up a map and populates it with 100 markers, then initializes the MarkerClusterer to group them.
```javascript
function initialize() { var center = new google.maps.LatLng(37.4419, -122.1419); var map = new google.maps.Map(document.getElementById("map"), { zoom: 3, center: center, mapTypeId: google.maps.MapTypeId.ROADMAP, }); var markers = []; for (var i = 0; i < 100; i++) { var dataPhoto = data.photos[i]; var latLng = new google.maps.LatLng( dataPhoto.latitude, dataPhoto.longitude ); var marker = new google.maps.Marker({ position: latLng, }); markers.push(marker); } var markerCluster = new MarkerClusterer(map, markers); } google.maps.event.addDomListener(window, "load", initialize);
```
--------------------------------
### Initialize MarkerClustererPlus and Event Listeners
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/examples/events_example.html
Sets up a Google Map with 100 markers clustered via MarkerClustererPlus and attaches click, contextmenu, mouseover, and mouseout listeners to the cluster objects.
```javascript
function initialize() { var center = new google.maps.LatLng(37.4419, -122.1419); var map = new google.maps.Map(document.getElementById("map"), { zoom: 3, center: center, mapTypeId: google.maps.MapTypeId.ROADMAP, }); var markers = []; for (var i = 0; i < 100; i++) { var dataPhoto = data.photos[i]; var latLng = new google.maps.LatLng( dataPhoto.latitude, dataPhoto.longitude ); var marker = new google.maps.Marker({ position: latLng, }); markers.push(marker); } var markerCluster = new MarkerClusterer(map, markers, { averageCenter: true, }); google.maps.event.addListener(markerCluster, "click", function (c) { log("click: "); log("—Center of cluster: " + c.getCenter()); log("—Number of managed markers in cluster: " + c.getSize()); var m = c.getMarkers(); var p = []; for (var i = 0; i < m.length; i++) { p.push(m[i].getPosition()); } log("—Locations of managed markers: " + p.join(", ")); }); google.maps.event.addListener( markerCluster, "contextmenu", function (c) { log("contextmenu: "); log("—Center of cluster: " + c.getCenter()); log("—Number of managed markers in cluster: " + c.getSize()); } ); google.maps.event.addListener(markerCluster, "mouseover", function (c) { log("mouseover: "); log("—Center of cluster: " + c.getCenter()); log("—Number of managed markers in cluster: " + c.getSize()); }); google.maps.event.addListener(markerCluster, "mouseout", function (c) { log("mouseout: "); log("—Center of cluster: " + c.getCenter()); log("—Number of managed markers in cluster: " + c.getSize()); }); } function log(h) { document.getElementById("log").innerHTML += h + " "; } google.maps.event.addDomListener(window, "load", initialize);
```
--------------------------------
### MarkerClusterer Constructor and Options
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
This section details how to initialize the MarkerClusterer with a map, markers, and various configuration options to customize clustering behavior and appearance.
```APIDOC
## MarkerClusterer Constructor
Creates a new MarkerClusterer instance to manage and cluster markers on a Google Map. The constructor accepts the map, an optional array of markers, and configuration options.
### Method
`new MarkerClusterer(map: google.maps.Map, markers?: google.maps.Marker[], options?: MarkerClustererOptions)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
import MarkerClusterer from '@googlemaps/markerclustererplus';
// Initialize Google Map
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(37.4419, -122.1419),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create markers
const markers = [];
const locations = [
{ lat: 37.7749, lng: -122.4194 },
{ lat: 34.0522, lng: -118.2437 },
{ lat: 40.7128, lng: -74.0060 },
{ lat: 41.8781, lng: -87.6298 },
{ lat: 29.7604, lng: -95.3698 }
];
locations.forEach(location => {
const marker = new google.maps.Marker({
position: new google.maps.LatLng(location.lat, location.lng)
});
markers.push(marker);
});
// Create MarkerClusterer with options
const markerClusterer = new MarkerClusterer(map, markers, {
gridSize: 60, // Cluster grid size in pixels (default: 60)
maxZoom: 15, // Max zoom level for clustering (default: null)
minimumClusterSize: 2, // Min markers to form cluster (default: 2)
zoomOnClick: true, // Zoom when cluster clicked (default: true)
averageCenter: true, // Position cluster at average of markers (default: false)
ignoreHidden: false, // Ignore hidden markers (default: false)
title: 'Click to zoom' // Tooltip for clusters
});
```
## MarkerClustererOptions Interface
Configuration options passed to the MarkerClusterer constructor for customizing clustering behavior, appearance, and interaction.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
interface MarkerClustererOptions {
gridSize?: number; // Grid size in pixels (default: 60)
maxZoom?: number; // Max zoom for clustering (default: null)
zoomOnClick?: boolean; // Zoom on cluster click (default: true)
averageCenter?: boolean; // Use average position (default: false)
minimumClusterSize?: number; // Min markers for cluster (default: 2)
zIndex?: number; // Z-index of clusters
ignoreHidden?: boolean; // Ignore hidden markers (default: false)
title?: string; // Cluster tooltip text
calculator?: Calculator; // Custom calculator function
clusterClass?: string; // CSS class for clusters (default: "cluster")
styles?: ClusterIconStyle[]; // Array of cluster icon styles
enableRetinaIcons?: boolean; // Support Retina displays (default: false)
batchSize?: number; // Markers per batch (default: 2000)
batchSizeIE?: number; // Markers per batch for IE (default: 500)
imagePath?: string; // Path to cluster images
imageExtension?: string; // Image file extension (default: "png")
imageSizes?: number[]; // Array of image sizes
ariaLabelFn?: (text: string) => string; // Accessibility label function
}
```
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Configure MarkerClustererPlus Styles and Initialization
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/examples/dynamic_icon_url_example.html
Defines custom cluster styles and initializes the map with a dynamic calculator for cluster icons.
```javascript
const styleCluster = [ MarkerClusterer.withDefaultStyle({ width: 25, height: 32, anchorIcon: [16, 12.5], textColor: "red", textSize: 10, }), MarkerClusterer.withDefaultStyle({ width: 50, height: 64, anchorIcon: [32, 25], textColor: "yellow", textSize: 10, }), MarkerClusterer.withDefaultStyle({ width: 100, height: 128, anchorIcon: [64, 50], textColor: "green", textSize: 10, }), ]; function initialize() { var center = new google.maps.LatLng(37.4419, -122.1419); var map = new google.maps.Map(document.getElementById("map"), { zoom: 3, center: center, mapTypeId: google.maps.MapTypeId.ROADMAP, }); var markers = []; for (var i = 0; i < 100; i++) { var dataPhoto = data.photos[i]; var latLng = new google.maps.LatLng( dataPhoto.latitude, dataPhoto.longitude ); var marker = new google.maps.Marker({ position: latLng, }); markers.push(marker); } var markerCluster = new MarkerClusterer(map, markers, { styles: styleCluster, calculator: (clusterMarkers, numStyles) => { let index = 0; const count = clusterMarkers.length; let dv = count; while (dv !== 0) { dv = Math.floor(dv / 10); index++; } const iconUrl = `https://chart.googleapis.com/chart?chs=150x150&chd=t:${count},${markers.length}&cht=p3&chf=bg,s,FFFFFF00`; index = Math.min(index, numStyles); return { text: count.toString(), url: iconUrl, index: index, title: "", }; }, }); } google.maps.event.addDomListener(window, "load", initialize);
```
--------------------------------
### JavaScript MarkerClustererPlus Implementation
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/examples/advanced_example.html
Configures cluster styles and initializes the map with marker clustering logic.
```javascript
var styles = [ [ MarkerClusterer.withDefaultStyle({ width: 35, height: 35, url: "../images/people35.png", textColor: "#ff00ff", textSize: 10, }), MarkerClusterer.withDefaultStyle({ width: 45, height: 45, url: "../images/people45.png", textColor: "#ff0000", textSize: 11, }), MarkerClusterer.withDefaultStyle({ width: 55, height: 55, url: "../images/people55.png", textColor: "#ffffff", textSize: 12, }), ], [ MarkerClusterer.withDefaultStyle({ url: "../images/conv30.png", width: 30, height: 27, anchorText: [-3, 0], anchorIcon: [27, 28], textColor: "#ff00ff", textSize: 10, }), MarkerClusterer.withDefaultStyle({ url: "../images/conv40.png", width: 40, height: 36, anchorText: [-4, 0], anchorIcon: [36, 37], textColor: "#ff0000", textSize: 11, }), MarkerClusterer.withDefaultStyle({ url: "../images/conv50.png", width: 50, height: 45, anchorText: [-5, 0], anchorIcon: [45, 46], textColor: "#0000ff", textSize: 12, }), ], [ MarkerClusterer.withDefaultStyle({ url: "../images/heart30.png", width: 30, height: 26, anchorIcon: [26, 15], textColor: "#ff00ff", textSize: 10, }), MarkerClusterer.withDefaultStyle({ url: "../images/heart40.png", width: 40, height: 35, anchorIcon: [35, 20], textColor: "#ff0000", textSize: 11, }), MarkerClusterer.withDefaultStyle({ url: "../images/heart50.png", width: 50, height: 44, anchorIcon: [44, 25], textSize: 12, }), ], [ { width: 30, height: 30, className: "custom-clustericon-1", }, { width: 40, height: 40, className: "custom-clustericon-2", }, { width: 50, height: 50, className: "custom-clustericon-3", }, ], ]; var markerClusterer = null; var map = null; var imageUrl = "https://chart.apis.google.com/chart?cht=mm&chs=24x32&" + "chco=FFFFFF,008CFF,000000&ext=.png"; google.maps.event.addDomListener(window, "load", initialize); function refreshMap() { if (markerClusterer) { markerClusterer.clearMarkers(); } var markers = []; var markerImage = new google.maps.MarkerImage( imageUrl, new google.maps.Size(24, 32) ); for (var i = 0; i < 1000; ++i) { var latLng = new google.maps.LatLng( data.photos[i].latitude, data.photos[i].longitude ); var marker = new google.maps.Marker({ position: latLng, icon: markerImage, }); markers.push(marker); } var zoom = parseInt(document.getElementById("zoom").value, 10); var size = parseInt(document.getElementById("size").value, 10); var style = parseInt(document.getElementById("style").value, 10); zoom = zoom == -1 ? null : zoom; size = size == -1 ? null : size; style = style == -1 ? null : style; markerClusterer = new MarkerClusterer(map, markers, { maxZoom: zoom, gridSize: size, styles: styles[style], clusterClass: style === 3 ? "custom-clustericon" : undefined, }); } function initialize() { map = new google.maps.Map(document.getElementById("map"), { zoom: 2, center: new google.maps.LatLng(39.91, 116.38), mapTypeId: google.maps.MapTypeId.ROADMAP, }); var refresh = document.getElementById("refresh"); google.maps.event.addDomListener(refresh, "click", refreshMap); var clear = document.getElementById("clear"); google.maps.event.addDomListener(clear, "click", clearClusters); refreshMap(); } function clearClusters(e) { e.preventDefault(); e.stopPropagation(); markerClusterer.clearMarkers(); }
```
--------------------------------
### Manage Clusterer Properties
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Use getter and setter methods to modify clusterer configuration at runtime. Call repaint() after updates to apply changes to the map.
```javascript
// Grid size - cluster grid in pixels
console.log('Grid size:', markerClusterer.getGridSize());
markerClusterer.setGridSize(80);
// Max zoom level
console.log('Max zoom:', markerClusterer.getMaxZoom());
markerClusterer.setMaxZoom(14);
// Minimum cluster size
console.log('Min cluster size:', markerClusterer.getMinimumClusterSize());
markerClusterer.setMinimumClusterSize(3);
// Zoom on click behavior
console.log('Zoom on click:', markerClusterer.getZoomOnClick());
markerClusterer.setZoomOnClick(false);
// Average center positioning
console.log('Average center:', markerClusterer.getAverageCenter());
markerClusterer.setAverageCenter(true);
// Ignore hidden markers
console.log('Ignore hidden:', markerClusterer.getIgnoreHidden());
markerClusterer.setIgnoreHidden(true);
// Enable Retina icons
console.log('Retina icons:', markerClusterer.getEnableRetinaIcons());
markerClusterer.setEnableRetinaIcons(true);
// Cluster title/tooltip
console.log('Title:', markerClusterer.getTitle());
markerClusterer.setTitle('Click to see markers');
// Z-index
console.log('Z-index:', markerClusterer.getZIndex());
markerClusterer.setZIndex(1000);
// Image path and extension
console.log('Image path:', markerClusterer.getImagePath());
markerClusterer.setImagePath('/assets/clusters/m');
markerClusterer.setImageExtension('png');
// Styles array
console.log('Styles:', markerClusterer.getStyles());
markerClusterer.setStyles(newStyles);
// Cluster CSS class
console.log('Cluster class:', markerClusterer.getClusterClass());
markerClusterer.setClusterClass('my-cluster');
// Apply changes
markerClusterer.repaint();
```
--------------------------------
### Handle Cluster Events
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Attach listeners to cluster interactions like clicks and mouse movements, or monitor the clustering lifecycle.
```javascript
// Click event - fired when a cluster is clicked
google.maps.event.addListener(markerClusterer, 'click', (cluster) => {
console.log('Clicked cluster at:', cluster.getCenter());
console.log('Markers in cluster:', cluster.getSize());
// Get all markers in this cluster
const markersInCluster = cluster.getMarkers();
markersInCluster.forEach(marker => {
console.log('Marker position:', marker.getPosition());
});
});
// Context menu (right-click) event
google.maps.event.addListener(markerClusterer, 'contextmenu', (cluster) => {
console.log('Right-clicked cluster with', cluster.getSize(), 'markers');
});
// Mouseover event
google.maps.event.addListener(markerClusterer, 'mouseover', (cluster) => {
console.log('Mouse entered cluster:', cluster.getCenter());
});
// Mouseout event
google.maps.event.addListener(markerClusterer, 'mouseout', (cluster) => {
console.log('Mouse left cluster');
});
// Clustering begin event
google.maps.event.addListener(markerClusterer, 'clusteringbegin', (mc) => {
console.log('Clustering started, processing', mc.getTotalMarkers(), 'markers');
});
// Clustering end event
google.maps.event.addListener(markerClusterer, 'clusteringend', (mc) => {
console.log('Clustering complete:', mc.getTotalClusters(), 'clusters formed');
});
```
--------------------------------
### Clusterer Utility Methods
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Methods for repainting, fitting the map, and retrieving cluster data.
```APIDOC
## repaint
### Description
Recalculates and redraws all marker clusters from scratch. Useful after changing clusterer properties.
## fitMapToMarkers
### Description
Adjusts the map viewport to fit all markers managed by the clusterer within the visible bounds.
### Parameters
- **padding** (number/object) - Optional - Padding in pixels or an object with top, right, bottom, left properties.
## getMarkers / getClusters
### Description
Retrieve arrays of all markers managed by the clusterer or all current clusters.
```
--------------------------------
### Lint and format code
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/CONTRIBUTING.md
Use these commands to check code style and automatically fix formatting issues.
```bash
npm run lint
npm run format # will fix some issues
```
--------------------------------
### Implement Custom Calculator Function
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Define a function to determine the cluster label text and style index based on the number of markers. The calculator can be set during initialization or updated later.
```javascript
// Custom calculator that shows "Many" for large clusters
function customCalculator(markers, numStyles) {
const count = markers.length;
let index = 0;
let text = '';
if (count < 10) {
text = count.toString();
index = 1;
} else if (count < 100) {
text = count.toString();
index = 2;
} else if (count < 1000) {
text = Math.floor(count / 100) + '00+';
index = 3;
} else {
text = 'Many';
index = Math.min(numStyles, 4);
}
return {
text: text,
index: index,
title: `Cluster of ${count} markers`
};
}
const markerClusterer = new MarkerClusterer(map, markers, {
calculator: customCalculator
});
// Or set/update calculator later
markerClusterer.setCalculator(customCalculator);
```
--------------------------------
### Include MarkerClustererPlus via unpkg
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/README.md
Include the UMD package directly in an HTML document using a unpkg link. The loader will be available as `MarkerClusterer`.
```html
```
--------------------------------
### Include MarkerClustererPlus via CDN
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
HTML script tag to include the library directly in a web page.
```html
```
--------------------------------
### Marker Management Methods
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Methods for adding, removing, and clearing markers from the clusterer instance.
```APIDOC
## addMarker / addMarkers
### Description
Adds one or multiple markers to the clusterer. Clusters are automatically redrawn unless nodraw is set to true.
### Parameters
- **marker/markers** (google.maps.Marker/Array) - Required - The marker or array of markers to add.
- **nodraw** (boolean) - Optional - If true, prevents immediate redrawing of the clusters.
## removeMarker / removeMarkers
### Description
Removes one or multiple markers from the clusterer. Returns true if the marker(s) were successfully removed.
### Parameters
- **marker/markers** (google.maps.Marker/Array) - Required - The marker or array of markers to remove.
- **nodraw** (boolean) - Optional - If true, prevents immediate redrawing of the clusters.
## clearMarkers
### Description
Removes all clusters and markers from the map and clears all managed markers from the clusterer.
```
--------------------------------
### Retrieve markers and clusters
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Access the underlying arrays of markers and clusters managed by the instance.
```javascript
// Get all markers
const allMarkers = markerClusterer.getMarkers();
console.log('Managing', allMarkers.length, 'markers');
// Get total count directly
console.log('Total markers:', markerClusterer.getTotalMarkers());
// Get all current clusters
const allClusters = markerClusterer.getClusters();
console.log('Current clusters:', allClusters.length);
// Get total cluster count
console.log('Total clusters:', markerClusterer.getTotalClusters());
// Iterate through clusters
allClusters.forEach(cluster => {
console.log('Cluster center:', cluster.getCenter());
console.log('Markers in cluster:', cluster.getSize());
console.log('Cluster markers:', cluster.getMarkers());
console.log('Cluster bounds:', cluster.getBounds());
});
```
--------------------------------
### Define Custom Cluster Styles
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Configure visual properties for clusters using image-based styles or CSS classes. Pass the styles array to the MarkerClusterer options.
```javascript
// Create custom styles for different cluster sizes
const customStyles = [
// Style for small clusters (< 10 markers)
MarkerClusterer.withDefaultStyle({
url: '/images/cluster-small.png',
width: 35,
height: 35,
textColor: '#ffffff',
textSize: 10,
anchorText: [0, 0], // [yOffset, xOffset] from center
anchorIcon: [17, 17] // [yOffset, xOffset] for icon position
}),
// Style for medium clusters (10-99 markers)
MarkerClusterer.withDefaultStyle({
url: '/images/cluster-medium.png',
width: 45,
height: 45,
textColor: '#ffffff',
textSize: 12
}),
// Style for large clusters (100+ markers)
MarkerClusterer.withDefaultStyle({
url: '/images/cluster-large.png',
width: 55,
height: 55,
textColor: '#ffffff',
textSize: 14,
fontWeight: 'bold',
fontFamily: 'Arial, sans-serif'
})
];
// CSS-only clusters (no images)
const cssOnlyStyles = [
{ width: 30, height: 30, className: 'cluster-small' },
{ width: 40, height: 40, className: 'cluster-medium' },
{ width: 50, height: 50, className: 'cluster-large' }
];
const markerClusterer = new MarkerClusterer(map, markers, {
styles: customStyles,
clusterClass: 'custom-cluster' // Base CSS class
});
```
--------------------------------
### Add markers to clusterer
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Use addMarker or addMarkers to include markers in the clusterer. Set the optional nodraw parameter to true to prevent immediate redrawing during batch operations.
```javascript
// Add a single marker
const newMarker = new google.maps.Marker({
position: new google.maps.LatLng(51.5074, -0.1278),
title: 'London'
});
markerClusterer.addMarker(newMarker);
// Add single marker without immediate redraw
markerClusterer.addMarker(newMarker, true);
// Add multiple markers at once
const moreMarkers = [
new google.maps.Marker({ position: new google.maps.LatLng(48.8566, 2.3522) }),
new google.maps.Marker({ position: new google.maps.LatLng(52.5200, 13.4050) }),
new google.maps.Marker({ position: new google.maps.LatLng(55.7558, 37.6173) })
];
markerClusterer.addMarkers(moreMarkers);
// Add markers without redraw, then manually repaint
markerClusterer.addMarkers(moreMarkers, true);
markerClusterer.repaint();
```
--------------------------------
### CSS Styles for Map and Clusters
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/examples/advanced_example.html
Defines the layout for the map container and custom CSS-based cluster icons.
```css
body { margin: 0; padding: 10px 20px 20px; font-family: Arial; font-size: 16px; } #map-container { padding: 6px; border-width: 1px; border-style: solid; border-color: #ccc #ccc #999 #ccc; -webkit-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px; -moz-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px; box-shadow: rgba(64, 64, 64, 0.1) 0 2px 5px; width: 800px; } #map { width: 800px; height: 400px; } #actions { list-style: none; padding: 0; } #inline-actions { padding-top: 10px; } .item { margin-left: 20px; } .custom-clustericon { background: var(--cluster-color); color: #fff; border-radius: 100%; font-weight: bold; font-size: 15px; display: flex; align-items: center; } .custom-clustericon::before, .custom-clustericon::after { content: ""; display: block; position: absolute; width: 100%; height: 100%; transform: translate(-50%, -50%); top: 50%; left: 50%; background: var(--cluster-color); opacity: 0.2; border-radius: 100%; } .custom-clustericon::before { padding: 7px; } .custom-clustericon::after { padding: 14px; } .custom-clustericon-1 { --cluster-color: #00a2d3; } .custom-clustericon-2 { --cluster-color: #ff9b00; } .custom-clustericon-3 { --cluster-color: #ff6969; }
```
--------------------------------
### Fit map to markers
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Adjusts the map viewport to ensure all managed markers are visible, with optional padding.
```javascript
// Fit map to show all markers
markerClusterer.fitMapToMarkers();
// Fit with padding (in pixels)
markerClusterer.fitMapToMarkers(50);
// Fit with specific padding per side
markerClusterer.fitMapToMarkers({
top: 100,
right: 50,
bottom: 100,
left: 50
});
```
--------------------------------
### Repaint clusters
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Forces a recalculation and redraw of all clusters. Necessary after modifying clusterer properties or marker visibility.
```javascript
// Change properties
markerClusterer.setGridSize(80);
markerClusterer.setMaxZoom(12);
// Repaint to apply changes
markerClusterer.repaint();
// Also useful after changing marker visibility when ignoreHidden is true
markerClusterer.setIgnoreHidden(true);
markers.forEach((marker, index) => {
marker.setVisible(index % 2 === 0); // Hide every other marker
});
markerClusterer.repaint();
```
--------------------------------
### Define MarkerClustererOptions Interface
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
TypeScript interface defining the available configuration properties for the MarkerClusterer constructor.
```typescript
interface MarkerClustererOptions {
gridSize?: number; // Grid size in pixels (default: 60)
maxZoom?: number; // Max zoom for clustering (default: null)
zoomOnClick?: boolean; // Zoom on cluster click (default: true)
averageCenter?: boolean; // Use average position (default: false)
minimumClusterSize?: number; // Min markers for cluster (default: 2)
zIndex?: number; // Z-index of clusters
ignoreHidden?: boolean; // Ignore hidden markers (default: false)
title?: string; // Cluster tooltip text
calculator?: Calculator; // Custom calculator function
clusterClass?: string; // CSS class for clusters (default: "cluster")
styles?: ClusterIconStyle[]; // Array of cluster icon styles
enableRetinaIcons?: boolean; // Support Retina displays (default: false)
batchSize?: number; // Markers per batch (default: 2000)
batchSizeIE?: number; // Markers per batch for IE (default: 500)
imagePath?: string; // Path to cluster images
imageExtension?: string; // Image file extension (default: "png")
imageSizes?: number[]; // Array of image sizes
ariaLabelFn?: (text: string) => string; // Accessibility label function
}
```
--------------------------------
### MarkerClustererPlus CSS Styles
Source: https://github.com/googlemaps/js-markerclustererplus/blob/main/examples/speed_test_example.html
Defines the layout and visual appearance for the map container and marker list panel.
```css
body { margin: 0; padding: 0; font-family: Arial; font-size: 14px; } #panel { float: left; width: 300px; height: 550px; } #map-container { margin-left: 300px; } #map { width: 100%; height: 550px; } #markerlist { height: 400px; margin: 10px 5px 0 10px; overflow: auto; } .title { border-bottom: 1px solid #e0ecff; overflow: hidden; width: 256px; cursor: pointer; padding: 2px 0; display: block; color: #000; text-decoration: none; } .title:visited { color: #000; } .title:hover { background: #e0ecff; } #timetaken { color: #f00; } .info { width: 200px; } .info img { border: 0; } .info-body { width: 200px; height: 200px; line-height: 200px; margin: 2px 0; text-align: center; overflow: hidden; } .info-img { height: 220px; width: 200px; }
```
--------------------------------
### Remove markers from clusterer
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Use removeMarker or removeMarkers to remove markers. These methods return a boolean indicating success.
```javascript
// Remove a single marker
const wasRemoved = markerClusterer.removeMarker(marker);
console.log('Marker removed:', wasRemoved); // true or false
// Remove without immediate redraw
markerClusterer.removeMarker(marker, true);
// Remove multiple markers
const markersToRemove = [marker1, marker2, marker3];
const anyRemoved = markerClusterer.removeMarkers(markersToRemove);
console.log('Any markers removed:', anyRemoved);
// Remove markers without redraw, then manually repaint
markerClusterer.removeMarkers(markersToRemove, true);
markerClusterer.repaint();
```
--------------------------------
### Clear all markers
Source: https://context7.com/googlemaps/js-markerclustererplus/llms.txt
Removes all managed markers and clusters from the map.
```javascript
// Clear all markers and clusters
markerClusterer.clearMarkers();
// Verify markers are cleared
console.log('Total markers:', markerClusterer.getTotalMarkers()); // 0
console.log('Total clusters:', markerClusterer.getTotalClusters()); // 0
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.