Core Concepts of Sources and Layers

Understand sources and layers, and learn to add, reuse, reorder, check, and remove map resources.

🎯 Introduction

By the end of this article, you will be able to add application data to a map, reuse it across layers, and handle layer order, removal, and style reloads.


🧱 Sources supply data; layers define rendering

A source tells the map what data is available, while a layer defines how to render it. This separation lets you render the same road data as a wide background line and a narrow centerline without copying the data.

map.addSource('places', {
    type: 'geojson',
    data: {
        type: 'FeatureCollection',
        features: [],
    },
})

map.addLayer({
    id: 'place-circles',
    type: 'circle',
    source: 'places',
    paint: {
        'circle-radius': 7,
        'circle-color': '#2563eb',
    },
})

places is the source ID and place-circles is the layer ID. Source IDs must be unique among sources, and layer IDs among layers. These IDs are used to query, update, and remove resources later.


🗺 Common layer types

TypeSuitable content
circlePoint locations and circles sized by numeric values
lineRoutes, tracks, and boundaries
fillPolygon features such as administrative areas and parcels
symbolIcons and text labels
rasterImagery, raster tiles, and rendered map images

Points represent locations, lines represent paths, and polygons represent enclosed areas. Choose a layer type based on the geometry first, then the visual representation you need.

The component below initially registers only a source, so no application data is visible. Add the visible layers with the button to render the same source using fill, line, circle, and symbol. This demonstrates how sources store data while layers define its appearance.

The source exists. Its data becomes visible when you show the layers.

🥞 Reuse data and control layer order

An area often needs both a translucent fill and a clear outline. Store its coordinates once in the areas source and let both a fill layer and a line layer read it:

map.addLayer({
    id: 'area-fill',
    type: 'fill',
    source: 'areas',
    paint: { 'fill-color': '#60a5fa', 'fill-opacity': 0.25 },
})

map.addLayer({
    id: 'area-outline',
    type: 'line',
    source: 'areas',
    paint: { 'line-color': '#2563eb', 'line-width': 2 },
})

This avoids duplicating area data. One setData() call on the areas source updates both the fill and outline.

Layers render in style order, with later layers covering earlier ones. Add area-fill before area-outline so the outline appears above the fill.

To change the order at runtime, call:

map.moveLayer('area-outline')
map.moveLayer('area-fill', 'area-outline')

The first call moves the outline above all layers; the second moves the fill before the outline, placing it underneath.

The component below renders a purple polygon, an orange line, and green points from one source. Click “Move points below polygon” to see how drawing order changes which features cover others:


🔎 Check and remove resources

Map modules may open and close repeatedly. For example, opening an area module adds its source and layers, and closing it removes them.

Adding the same ID twice causes an error. Check with getSource() and getLayer() before adding resources. Here is the complete setup function:

function addAreaResources(areaGeoJSON) {
    if (!map.getSource('areas')) {
        map.addSource('areas', {
            type: 'geojson',
            data: areaGeoJSON,
        })
    }

    if (!map.getLayer('area-fill')) {
        map.addLayer({
            id: 'area-fill',
            type: 'fill',
            source: 'areas',
            paint: { 'fill-color': '#60a5fa', 'fill-opacity': 0.25 },
        })
    }

    if (!map.getLayer('area-outline')) {
        map.addLayer({
            id: 'area-outline',
            type: 'line',
            source: 'areas',
            paint: { 'line-color': '#2563eb', 'line-width': 2 },
        })
    }
}

Remove resources in reverse order. Mapbox does not allow a source to be removed while layers still reference it, so remove all dependent layers first:

function removeAreaResources() {
    if (map.getLayer('area-outline')) map.removeLayer('area-outline')
    if (map.getLayer('area-fill')) map.removeLayer('area-fill')
    if (map.getSource('areas')) map.removeSource('areas')
}

Here, getLayer() and getSource() check whether an ID is registered with Mapbox; they do not query application data. These checks make the add and remove functions safe to call repeatedly.

The component below adds and removes an area source, fill layer, and outline layer. Its remove button always removes the layers before the source:

Resources removed

🧭 Position layers in the Standard style

Mapbox Standard's basemap structure can change with style updates. Avoid depending on internal basemap layer IDs. Use slot when adding a layer to position application data in a more stable location:

map.addLayer({
    id: 'area-fill',
    type: 'fill',
    source: 'areas',
    slot: 'middle',
    paint: {
        'fill-color': '#60a5fa',
        'fill-opacity': 0.35,
    },
})
slotApplication layer position
bottomAbove basemap polygon features
middleAbove roads and behind 3D buildings
topAbove point-of-interest labels and behind place and transit labels
UnspecifiedAbove Standard's built-in layers

Within a slot, use moveLayer() to reorder application layers. Traditional styles such as light-v11 do not have these slots; use the second argument of addLayer or moveLayer() instead.

To configure Standard's theme and label visibility, you do not need to iterate through basemap layers. Set config at initialization or update it at runtime:

const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/standard',
    config: {
        basemap: {
            theme: 'monochrome',
            showPointOfInterestLabels: false,
        },
    },
})

map.setConfigProperty('basemap', 'lightPreset', 'dusk')

theme selects the basemap theme, showPointOfInterestLabels controls point-of-interest labels, and lightPreset accepts dawn, day, dusk, or night. These settings apply only to Standard. For traditional styles, change layer properties or replace the style.


🔄 Restore application resources after a style reload

Use setStyle() to switch between light and dark basemaps. It replaces the entire style, including both basemap layers and sources and layers added at runtime.

After this switch, the old style's areas source, area-fill layer, and area-outline layer are gone:

map.setStyle('mapbox://styles/mapbox/dark-v11')

To keep displaying the application areas, wait for the new style to load, then add the sources and layers to it:

map.on('style.load', () => {
    addAreaResources(areaGeoJSON)
})
map.setStyle('mapbox://styles/mapbox/light-v11')

areaGeoJSON is the area data currently held by the application. style.load indicates that the new style can accept sources and layers. The earlier addAreaResources() function restores these resources while checking for duplicate IDs.

First click “Switch style only” below: the green application area disappears with the old style. Then click “Switch and restore area”: the component re-adds the source and layers after style.load:

The data area is visible

🧾 Summary

  • Sources store data; layers define how it is displayed.
  • Multiple layers can reuse one source.
  • Layer order determines overlap; adjust it with moveLayer.
  • Check existence with getSource and getLayer before adding or removing resources.
  • Remove layers that reference a source before removing the source.
  • Standard uses slot for layer placement and config for basemap appearance.
  • Restore runtime application resources after switching styles.

❓ Questions and answers

Q1: Why can't I assign a color directly to a source?

A source supplies only data. Color is a rendering rule and belongs in a layer's paint properties.

Q2: Why use two layers for the same polygon data?

fill renders the interior and line renders a clear outline, allowing their styles to be controlled separately.

Q3: What does moveLayer('a', 'b') mean?

It moves a below b, placing it before b in the style's layer list.


🧪 Exercises

  1. Add fill and outline layers for the same polygon source.
  2. Write an addBusinessLayers function that is safe to call repeatedly.
// Write your code here

🎉 You now understand the core uses of sources and layers!