mapboxGetActualMapBounds

Gitlab
A utility function that retrieves the actual map bounds ignoring any padding set on the map.
Added since: v0.1.0
Last changed:

Overview

A utility function that calculates the true viewport bounds of a Mapbox GL map instance, ignoring any padding that might be set on the map. This is particularly useful when you need to work with the actual visible area of the map without padding adjustments.

Usage

import { mapboxGetActualMapBounds } from '~/utils/mapboxGetActualMapBounds';

const map = new mapboxgl.Map({ ... });
const bounds = mapboxGetActualMapBounds(map, 50);
console.log(bounds); // [-180, -85, 180, 85] or actual bounds if map exists

API Reference

mapboxGetActualMapBounds()

Calculates the actual map bounds ignoring any padding set on the map.

PropDefaultType
map*
Map | null
The Mapbox GL map instance. If null, returns the default world bounds
padding
number
Optional padding in pixels to add to the bounds

Type Definitions

/**
 * A tuple representing map bounds in [westLng, southLat, eastLng, northLat] format
 */
type MapboxMapBounds = [number, number, number, number];

/**
 * Default world bounds used when no map is provided
 */
const DEFAULT_WORLD_BOUNDS: MapboxMapBounds = [-180, -85, 180, 85] as const;

/**
 * Gets the actual map bounds ignoring any padding set on the map.
 * 
 * @param map - The Mapbox GL map instance
 * @param padding - Optional padding in pixels to add to the bounds
 * @default 0
 * 
 * @returns MapboxMapBounds or DEFAULT_WORLD_BOUNDS if map is null
 */
export function mapboxGetActualMapBounds(
    map: Map | null,
    padding?: number
) => MapboxMapBounds;

Example

import { mapboxGetActualMapBounds } from '~/utils/mapboxGetActualMapBounds';

const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v11',
  center: [-74.5, 40],
  zoom: 9
});

// Get bounds without padding
const bounds = mapboxGetActualMapBounds(map);
console.log(bounds); // [westLng, southLat, eastLng, northLat]

// Get bounds with 50px padding
const paddedBounds = mapboxGetActualMapBounds(map, 50);

Changelog