Given a set of GeoJSON features finds the optimal bearing, zoom and center point for fitting all features in a Mapbox GL or MapLibre GL viewport. The optimal viewport is calculated by determining the optimal bearing and zoom level to present a minimum bounding rectangle (MBR) of all the given GeoJSON features. This can allow you to render more detailed, better fitting maps than the default bounding box behaviour which only describes a x/y aligned minimum bounding rectangle.
Preview
Usage
mapFitFeatures
returns an object describing the optimal center point (center
), bearing (bearing
) and zoom level
(zoom
) to display the given GeoJSON features in a given resolution map.
import { mapFitFeatures } from 'geojson-map-fit-mercator';
import maplibregl from 'maplibre-gl';
import mapData from './map-data.json' with { type: 'json' }; // Load GeoJSON data
const { bearing, center, zoom } = mapFitFeatures(
mapData,
[600, 300]
);
const map = new new maplibregl.Map({
container: 'map', // container ID for a 600px by 400px element
style: 'https://demotiles.maplibre.org/style.json',
center: center, // starting position [lng, lat]
zoom: zoom, // starting zoom
bearing: bearing // starting bearing
});
...
Padding
You can add padding around the features in the viewport by passing an object to the padding
option of mapFitFeatures
.
This padding object is identical to the Mapbox GL JS paddingOptions
object and MapLibre GL JS paddingOptions
object.
mapFitFeatures(
mapData,
[600, 300],
{
padding: {
top: 50,
bottom: 50,
left: 100,
right: 100
}
}
);
Bearing Preference
You can specify a preferred bearing for the map by passing the bearing
option to mapFitFeatures
. The preferred
bearing will be used to pick the preferred orientation of the map to fit the minimum bounding rectangle of the features.
This defaults to 0
which prefers to point the map in a northerly bearing.
mapFitFeatures(
mapData,
[600, 300],
{
preferredBearing: 180 // Prefer to point the map south
}
);
Additional Features and Documentation
A full set of options and parameter descriptions for mapFitFeatures
such as tile-size and zoom preferences are
described in the API section of the Readme.