Map Initialization and Camera Control

Configure the center, zoom, bearing, pitch, and bounds, and choose the right camera transition method.

🎯 Introduction

By the end of this article, you will be able to configure the initial camera view, fit the map to point, line, and polygon data, and choose camera transitions for different interactions.


🧱 Initialization options define the initial view

const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v11',
    center: [116.397, 39.909],
    zoom: 10,
    bearing: 20,
    pitch: 45,
})
OptionMeaningExample
containerDOM element or element ID that contains the mapmapContainer.value
styleMap style URL or style objectmapbox://styles/mapbox/light-v11
centerMap center[116.397, 39.909]
zoomZoom level; higher values show a smaller area in greater detail10
bearingClockwise rotation in degrees; 0 means north is up20
pitchTilt away from a straight-down view in degrees; 0 looks straight down45

Mapbox coordinate arrays always use [longitude, latitude]. Reversing the order can place the map far from the intended location or cause an error if the latitude is out of range.

The map below uses bearing: -25 and pitch: 55 to show how rotation and tilt work together:


🧭 Read and update the camera directly

const center = map.getCenter()
const zoom = map.getZoom()
const bearing = map.getBearing()
const pitch = map.getPitch()

map.setCenter([121.474, 31.230])
map.setZoom(12)
map.setBearing(0)
map.setPitch(30)

These set... methods immediately update individual camera properties. They work well for form-driven changes or restoring a known state. The center is returned as a LngLat object; read its values with center.lng and center.lat.


✨ Three camera transition methods

map.jumpTo({ center: [121.474, 31.230], zoom: 12 })

map.easeTo({
    center: [121.474, 31.230],
    zoom: 12,
    duration: 800,
})

map.flyTo({
    center: [121.474, 31.230],
    zoom: 12,
})
MethodTransitionCommon uses
jumpToImmediate changeRestore state or synchronize filtered results
easeToSmooth transitionFocus on a feature within the same area
flyToFlight animation with zoom changesNavigate between cities or regions

flyTo animations usually take longer. Use them when users need to follow movement between regions; prefer jumpTo or easeTo for routine navigation.

The three buttons below call their corresponding methods. Click them in sequence to compare immediate changes, smooth movement, and flight animations:


📐 Fit the camera to the data bounds

When an API returns several locations, a fixed center and zoom may leave some offscreen. fitBounds moves and zooms the map automatically so the entire dataset fits inside the container.

For example, suppose search results contain three locations in Beijing. Instead of calculating the center and zoom manually, extend the bounds with each coordinate:

const coordinates = [
    [116.32, 39.90],
    [116.40, 39.92],
    [116.48, 39.88],
]

const bounds = new mapboxgl.LngLatBounds()

coordinates.forEach((coordinate) => {
    bounds.extend(coordinate)
})

if (!bounds.isEmpty()) {
    map.fitBounds(bounds, {
        padding: 40,
        maxZoom: 15,
        duration: 800,
    })
}

LngLatBounds tracks the westernmost, southernmost, easternmost, and northernmost coordinates. fitBounds then calculates a suitable center and zoom for the container dimensions.

  • padding: 40: leave at least 40 pixels between the data and each edge of the map.
  • maxZoom: 15: limit zooming in so a single point or a small extent does not appear too close.
  • duration: 800: complete the camera transition in 800 milliseconds.

For a route, add all LineString coordinates to bounds; for an area, add the Polygon's exterior ring coordinates. With no data, the bounds remain empty, so call isEmpty() before deciding whether to fit the camera.

A, B, and C below mark the three example coordinates. fitBounds calculates the view automatically, keeping all three visible with space around the edges:


📦 Call resize when the container changes

When a sidebar expands, a dialog widens, or a hidden tab becomes visible, the canvas dimensions may not update automatically. Once the layout settles, call:

map.resize()

You can observe the container with ResizeObserver and call resize() when its dimensions change. A complete Vue component example appears in the practical section.


🧾 Summary

  • Coordinates use [longitude, latitude] order.
  • Higher zoom values show a smaller area in greater detail.
  • bearing controls rotation; pitch controls tilt.
  • jumpTo changes the view immediately, easeTo transitions smoothly, and flyTo suits navigation between regions.
  • fitBounds calculates a view from data bounds. Call resize() after layout changes.

❓ Questions and answers

Q1: Why does fitBounds zoom in too far?

A single point or very small extent can produce a high calculated zoom level. Set maxZoom to limit it.

Q2: Do I need to recreate the map to change its center?

No. Use setCenter or one of the three camera transition methods.

Q3: Does pitch change the data coordinates?

No. It changes only the camera angle, leaving source coordinates unchanged.


🧪 Exercises

  1. Switch between two cities with easeTo and compare the result with jumpTo.
  2. Calculate LngLatBounds for a set of points and specify padding and maxZoom.
// Write your code here

🎉 You now know how to control the map camera!