Skip to content

Fit to the bounds of a LineString

Replicates the MapLibre example Fit to the bounds of a LineString. Upstream folds the line’s coordinates into an LngLatBounds and calls map.fitBounds from a button. Here config.fitTo names the source, and the map opens already framed on the route. No coordinates are copied into the camera.

The camera frames the route from the first frame
fit-to-the-bounds-of-a-linestring.yaml
# yaml-language-server: $schema=https://docs.maplibre-yaml.org/schema/latest/map.schema.json
# Gallery twin of https://maplibre.org/maplibre-gl-js/docs/examples/fit-to-the-bounds-of-a-linestring/
# `config.fitTo` frames the initial camera on a source's data — the bounds
# walk zoomToFeature uses, applied to the whole source on load. The authored
# center/zoom stay as the fallback camera.
type: map
id: fit-to-the-bounds-of-a-linestring
config:
center: [-77.0214, 38.897]
zoom: 12
mapStyle: "https://tiles.openfreemap.org/styles/bright"
fitTo:
source: route
padding: 20
sources:
route:
type: geojson
data:
type: FeatureCollection
features:
- type: Feature
properties: {}
geometry:
type: LineString
coordinates:
- [-77.0366048812866, 38.89873175227713]
- [-77.03364372253417, 38.89876515143842]
- [-77.03364372253417, 38.89549195896866]
- [-77.02982425689697, 38.89549195896866]
- [-77.02400922775269, 38.89387200688839]
- [-77.01519012451172, 38.891416957534204]
- [-77.01521158218382, 38.892068305429156]
- [-77.00813055038452, 38.892051604275686]
- [-77.00832366943358, 38.89143365883688]
- [-77.00818419456482, 38.89082405874451]
- [-77.00815200805664, 38.88989712255097]
layers:
- id: route
type: line
source: route
layout:
line-join: round
line-cap: round
paint:
line-color: "#BF93E4"
line-width: 5
  • fitTo.source names an entry in sources:, and padding and maxZoom mirror MapLibre’s fitBounds options. The bounds come from the same walk the zoomToFeature click interaction uses, applied to the whole source.
  • Inline data: is framed at construction, so the camera never jumps. A url: source opens at the authored center/zoom and is framed once its first fetch lands. Later refreshes don’t re-fit.
  • center/zoom stay required. They are the camera before the data arrives, and the fallback when the fit can’t apply. Tiled sources (vector, raster) have no client-side extent and keep the authored camera, with a warning.
  • Upstream fits on a button click. The button itself is page chrome, not something the format expresses. The initial-camera fit is the declarative half.
  • Export class: exports-with-fallback. mlym emit --with-fallbacks computes the fitted center/zoom from the inline line for a 1024×768 reference viewport and writes them as the style’s root camera. This is reported as lossy, because a live map fits its own container. --strict refuses.