Map Styling and Data-Driven Expressions

Use paint, layout, and Mapbox expressions to vary color, size, and visibility by properties or zoom level.

🎯 Introduction

By the end of this article, you will be able to style features by status, category, and numeric values, and show appropriate detail at different zoom levels.


🧱 The roles of paint and layout

paint controls rendering properties such as color, opacity, line width, and circle radius. layout controls visibility, text content, icons, and symbol placement.

map.addLayer({
    id: 'places',
    type: 'circle',
    source: 'places',
    layout: { visibility: 'visible' },
    paint: {
        'circle-color': '#2563eb',
        'circle-radius': 7,
        'circle-opacity': 0.8,
    },
})

Each layer type supports different properties. For example, line-width cannot be used on a circle layer.


🎨 Calculate styles from feature properties

A circle layer normally draws all points with the same color and size. When points have different statuses and values, use expressions to read those fields and let Mapbox calculate a style for each point.

For example, these three features have different status and score values:

const places = {
    type: 'FeatureCollection',
    features: [
        {
            type: 'Feature',
            properties: { name: 'Location A', status: 'online', score: 20 },
            geometry: { type: 'Point', coordinates: [116.35, 39.91] },
        },
        {
            type: 'Feature',
            properties: { name: 'Location B', status: 'warning', score: 55 },
            geometry: { type: 'Point', coordinates: [116.40, 39.92] },
        },
        {
            type: 'Feature',
            properties: { name: 'Location C', status: 'offline', score: 90 },
            geometry: { type: 'Point', coordinates: [116.45, 39.89] },
        },
    ],
}

To use status for color and score for circle size, put expressions directly in paint:

map.addLayer({
    id: 'places',
    type: 'circle',
    source: 'places',
    paint: {
        'circle-color': [
            'match',
            ['get', 'status'],
            'online', '#16a34a',
            'warning', '#f59e0b',
            'offline', '#9ca3af',
            '#2563eb',
        ],
        'circle-radius': [
            'interpolate',
            ['linear'],
            ['get', 'score'],
            0, 7,
            100, 18,
        ],
    },
})

Mapbox evaluates the expressions separately for each feature:

FeatureProperty valuesResult
Location Aonline, 20Small green circle
Location Bwarning, 55Medium orange circle
Location Coffline, 90Large gray circle

['get', 'status'] reads the current feature's properties.status, and match maps statuses to colors. ['get', 'score'] reads the score, and interpolate calculates a continuous radius between 7 and 18 from that value.

This lets a single layer give different features different styles. You do not need separate sources for each status or JavaScript updates for individual circles.

Here is the rendered result. The number in each label is its score:


🧰 Choose among five common expressions

ExpressionPurposeExample
getRead a property of the current featureRead status
matchMap a finite set of categories to resultsGreen for online, gray for offline
caseChoose results using boolean conditionsShow an outline when selected
stepDivide values into threshold rangesIncrease circle size at counts of 10 and 100
interpolateVary styles continuously with a numberGradually enlarge circles as scores increase

Here are examples of case and step:

// Use a 3-pixel outline when selected is true; otherwise use no outline
'circle-stroke-width': [
    'case',
    ['==', ['get', 'selected'], true], 3,
    0,
]

// Radius is 5 below a count of 10, 8 from 10, and 12 from 100
'circle-radius': [
    'step', ['get', 'count'],
    5,
    10, 8,
    100, 12,
]

If a field may be missing, use coalesce for a default, such as ['coalesce', ['get', 'score'], 0]. Features without score then use 0 rather than passing null to a numeric expression.


🔍 Vary styles with zoom

zoom is the map's zoom level. At lower levels, users see a wider area, so roads and boundaries should be thinner. At neighborhood scale, thicker lines remain visible against the more detailed basemap.

The following expression defines two stops:

  • At zoom 9, the line width is 2px.
  • At zoom 14, the line width is 8px.
  • Between 9 and 14, Mapbox calculates intermediate widths. At 11.5, for example, the width is about 5px.
'line-width': [
    'interpolate', ['linear'], ['zoom'],
    9, 2,
    14, 8,
]

This keeps routes readable at different scales without changing route data. Because all features use the same width at a given zoom level, an expression that reads zoom is called a camera expression.

The two maps below use the same route and expression at different zoom levels. The left map shows a thin line from farther away; the right shows a thicker line up close:

Zoom 9: 2 px line width
Zoom 14: 8 px line width

A property expression reads properties to style features differently; a camera expression reads zoom to change the entire layer as the map zooms.


💡 Three common thematic maps

A thematic map emphasizes a particular application field. Rather than changing the basemap, it maps status, category, or values to color and size so users can compare features without opening each one.

QuestionExample fieldVisual representationExpression
Which locations are online, offline, or in a warning state?status: 'online'A fixed color for each statusmatch
Which areas have low, medium, or high risk?risk: 72Threshold-based categories with a color for eachstep
Which locations have larger values?count: 86Larger circles for larger valuesinterpolate

Colors by status

Statuses are discrete categories: there is no intermediate value between online and offline. Use match to assign green to online, gray to offline, and orange to warning, as shown in the earlier expression demo.

Colors by category

Risk scores are continuous numbers, but an application may need only low, medium, and high categories. Use step to divide them by threshold:

'fill-color': [
    'step', ['get', 'risk'],
    '#bbf7d0',
    40, '#fde68a',
    70, '#fca5a5',
]

Values below 40 are green, values from 40 are yellow, and values from 70 are red.

Sizes by value

When users need to compare quantities rather than fixed categories, vary circle size continuously:

'circle-radius': [
    'interpolate', ['linear'], ['get', 'count'],
    0, 6,
    100, 18,
]

At a count of 0, the radius is 6px; at 100, it is 18px. Mapbox calculates intermediate values. Set minimum and maximum sizes so small values remain visible and large values do not cover the map.

The three maps below use the same dataset to show status, value category, and differences in magnitude. Compare them to see when to use match, step, and interpolate.

Color by status: match
Color by level: step
Size by value: interpolate

When expressions have more than two or three nesting levels, define constants in the script and explain their application meaning:

const statusColor = [
    'match', ['get', 'status'],
    'online', '#16a34a',
    'offline', '#9ca3af',
    '#f59e0b',
]

map.setPaintProperty('places', 'circle-color', statusColor)

This avoids putting large nested arrays directly into layer configuration.


🧾 Summary

  • paint controls rendering; layout controls layout and visibility.
  • get reads feature properties.
  • match maps categories; case evaluates conditions.
  • Use step for ranges and interpolate for continuous changes.
  • Camera expressions using zoom vary styles with zoom level.
  • Extract complex expressions into constants with meaningful application names.

❓ Questions and answers

Q1: Why does the first result in step come before the thresholds?

It is the default result for values below the first threshold. Subsequent entries are threshold/result pairs.

Q2: Can an expression read a Vue ref directly?

No. Expressions run in Mapbox's style system. Pass dynamic application values through setPaintProperty, setFilter, or data updates.

Q3: Are more colors always better for thematic maps?

No. Categories should match the application's meaning and keep the legend easy to read.


🧪 Exercises

  1. Assign colors to three statuses with match, including a fallback for unknown statuses.
  2. Use interpolate to increase point radius from 4 to 10 between zoom levels 8 and 14.
// Write your code here

🎉 You now know how to create data-driven styles!