mapboxFocusSingleFeature() is a utility function that helps focus the map view on a specific GeoJSON feature. It intelligently handles both clustered and non-clustered features, automatically calculating the appropriate zoom level needed to break clustered features out of their clusters.
Behavior for unclustered features:
When the feature isn't clustered, simply fly to it.
map.flyTo() to center the map on the feature's coordinatesBehavior for clustered features:
When the feature is clustered, zoom to the minimum expansion zoom needed to break this feature out of the cluster.
import { mapboxFocusSingleFeature } from '~/utils/mapboxFocusSingleFeature';
// Focus on a non-clustered feature
mapboxFocusSingleFeature(map, supercluster, feature);
// Focus on a clustered feature with custom animation options
mapboxFocusSingleFeature(map, supercluster, feature, {
duration: 1000,
easing: (t) => t * (2 - t)
});
Focuses the map view on a single feature, handling both clustered and non-clustered features.
| Prop | Default | Type |
|---|---|---|
map* | Map | nullThe Mapbox GL map instance | |
supercluster* | SuperclusterThe Supercluster instance used for managing the clusters | |
feature* | Feature<Point, { cluster?: boolean }>The GeoJSON feature to focus on. Can be either a clustered or non-clustered feature | |
options | EasingOptionsOptional easing options for the map animation |
/**
* Focuses the map view on a single feature, handling both clustered and non-clustered features.
* For non-clustered features, it simply flies to the feature's location.
* For clustered features, it calculates the minimum zoom level needed to break the feature out of its cluster.
*
* @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 to focus on. Can be either a clustered or non-clustered feature.
* @param options - Optional easing options for the map animation.
*/
export function mapboxFocusSingleFeature(
map: Map | null,
supercluster: Supercluster,
feature: Feature<Point, { cluster?: boolean }>,
options?: EasingOptions,
): void;
const map = new mapboxgl.Map({ ... });
const supercluster = new Supercluster({ ... });
// Non-clustered feature
const pointFeature = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0, 0]
},
properties: {}
};
// Clustered feature
const clusteredFeature = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0, 0]
},
properties: {
cluster: true
}
};
// Focus on non-clustered feature
mapboxFocusSingleFeature(map, supercluster, pointFeature);
// Focus on clustered feature with custom animation
mapboxFocusSingleFeature(map, supercluster, clusteredFeature, {
duration: 1000,
easing: (t) => t * (2 - t)
});