mapboxFocusFeatures() is a utility that helps focus the map view on one or more GeoJSON features.
Behavior for a single feature:
This is a fallback behavior. For a better zoom level, use mapboxFocusSingleFeature.
map.flyTo() to center the map on the feature's coordinatesBehavior for multiple features:
This is the intended behavior.
map.fitBounds()import { mapboxFocusFeatures } from '~/utils/mapboxFocusFeatures';
// Focus on a single feature
mapboxFocusFeatures(map, [singleFeature], { duration: 1000 });
// Focus on multiple features
mapboxFocusFeatures(map, [feature1, feature2], { duration: 1000 });
Focuses the map view on one or more GeoJSON features.
| Prop | Default | Type |
|---|---|---|
map* | Map | nullThe Mapbox GL map instance | |
features* | MapboxFeaturesArray of GeoJSON features to focus on | |
options | EasingOptionsOptional easing options for the map animation |
/**
* Focuses the map view on one or more features by either flying to a single feature
* or fitting bounds to contain multiple features.
*
* @param map - The Mapbox GL map instance. If null, the function will return early.
* @param features - Array of GeoJSON features to focus on. Can be a single feature or multiple features.
* @param options - Optional easing options for the map animation.
*/
export function mapboxFocusFeatures(
map: Map | null,
features: MapboxFeatures,
options?: EasingOptions,
): void;
import { mapboxFocusFeatures } from '~/utils/mapboxFocusFeatures';
const map = new mapboxgl.Map({ /* ... */ });
const feature = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0, 0]
}
};
mapboxFocusFeatures(map, [feature], { duration: 1000 });
import { mapboxFocusFeatures } from '~/utils/mapboxFocusFeatures';
const map = new mapboxgl.Map({ /* ... */ });
const features = [
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0, 0]
}
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [1, 1]
}
}
];
mapboxFocusFeatures(map, features, { duration: 1000 });