mapboxExpandCluster() is a utility that enhances the default Mapbox cluster expansion behavior. While the default behavior only zooms enough to break up a cluster, this function zooms in as far as possible while ensuring all markers within the cluster remain visible in the viewport.
Behavior for small maps (width < 640px):
This is the fallback behavior, since it most likely returns the same result as the default zoom.
getClusterExpansionZoom() method of the Supercluster instance. (See Supercluster API)flyTo() method of the Map instance.Behavior for larger maps:
This is the intended behavior.
getLeaves() method of the Supercluster instance. (See Supercluster API)import { mapboxExpandCluster } from '~/utils/mapboxExpandCluster';
// Basic usage
mapboxExpandCluster(map, supercluster, clusterFeature);
// With custom easing options
mapboxExpandCluster(map, supercluster, clusterFeature, { padding: 50 });
Expands a Mapbox cluster by zooming to fit all contained markers within the viewport.
| Prop | Default | Type |
|---|---|---|
map* | Map | nullThe Mapbox GL map instance | |
supercluster* | SuperclusterThe Supercluster instance used for managing the clusters | |
feature* | Feature<Point, { cluster_id: number }>The GeoJSON feature representing the cluster to expand | |
options | EasingOptionsOptional easing options for the map animation |
/**
* Expands a Mapbox cluster by zooming to fit all contained markers within the viewport.
* Unlike the default cluster expansion which only zooms enough to break up the cluster,
* this function zooms in as far as possible while keeping all markers visible.
*
* @param map - The Mapbox GL map instance. If null, the function will return early.
* @param supercluster - The Supercluster instance used for managing the clusters.
* @param feature - The GeoJSON feature representing the cluster to expand.
* @param options - Optional easing options for the map animation.
*/
export function mapboxExpandCluster(
map: Map | null,
supercluster: Supercluster,
feature: Feature<Point, { cluster_id: number }>,
options: EasingOptions = { padding: 100 },
): void;
<script setup lang="ts">
import mapboxgl from 'mapbox-gl';
import Supercluster from 'supercluster';
import { mapboxExpandCluster } from '~/utils/mapboxExpandCluster';
// Initialize map and supercluster
const map = new mapboxgl.Map({ /* ... */ });
const supercluster = new Supercluster({ /* ... */ });
// Handle cluster click
map.on('click', 'clusters', (e) => {
const feature = e.features[0];
if (feature.properties?.cluster) {
mapboxExpandCluster(map, supercluster, feature);
}
});
</script>
<script setup lang="ts">
import { mapboxExpandCluster } from '~/utils/mapboxExpandCluster';
// Customize the animation and padding
mapboxExpandCluster(map, supercluster, clusterFeature, {
padding: 50,
duration: 1000,
easing: (t) => t * (2 - t) // ease-out-quad
});
</script>