mapboxFocusFeatures

Gitlab
A utility function for focusing the Mapbox GL map view on one or more GeoJSON features.
Added since: v0.1.0
Last changed:

Overview

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.

  1. Uses map.flyTo() to center the map on the feature's coordinates

Behavior for multiple features:
This is the intended behavior.

  1. Recursively adds the coordinates of all features to the map's bounds
  2. Fits the map bounds to contain all features using map.fitBounds()

Usage

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 });

API Reference

mapboxFocusFeatures()

Focuses the map view on one or more GeoJSON features.

PropDefaultType
map*
Map | null
The Mapbox GL map instance
features*
MapboxFeatures
Array of GeoJSON features to focus on
options
EasingOptions
Optional easing options for the map animation

Type Definitions

/**
 * 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;

Example

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 });

Changelog