Skip to main content

Map styles

You can use Mapbox GL JS to control many aspects of the map design, including styling custom data, tweaking your map's styling, adding fonts, creating data-driven visualizations, and more. You can use a map style designed by Mapbox's cartographers, such as Mapbox Standard, or create a custom map style by adjusting the map's colors, icons, and fonts to match your application's UI or company's brand.

GUIDE
Getting started: Map styles

Learn how Mapbox styles work and get started developing your map.

There are two approaches to customizing the look of the map:

  • Update map features dynamically at runtime using Mapbox GL JS API. Lighten or darken the map based on the time of day, personalize icons and map colors based on your users’ activity, switch languages dynamically, or increase the size of labels based on user preferences to improve legibility.
  • Create a custom map style with Mapbox Studio. Upload data, build styles from scratch, and style groups of layers together using style components. Publish your custom style and load it into your application. If you update the underlying data or you edit and publish updates to the style in Mapbox Studio, those changes will be reflected in your application.

These approaches are not mutually exclusive. You can load a custom style and update map features from that custom style in your application at runtime.

Mapbox Studio Manual

These guides cover working with the map style at runtime. For more information on how to create a custom map style in Mapbox Studio, see the Mapbox Studio Manual.


Set a style

Across the Mapbox ecosystem, the appearance of the map is determined by the map style. A Mapbox style is a JSON object that defines exactly how to draw a map. It defines almost everything related to a map's appearance. In Mapbox GL JS, you can set the style of the map when creating the map instance or at any point afterwards.

Choose a style

The style you choose for your application should reflect how your users will interact with the map and what they will use your application for. If you are not sure what style is right for you, we recommend getting started with the carefully designed, all-purpose Mapbox Standard style.

Load a style

Mapbox GL JS’s Map class provides an embeddable map interface. You can embed the map on a webpage, allow users to manipulate it with standard gestures, and more.

Default style

If you don’t specify a style when initializing a map, Mapbox GL JS will use the Mapbox Standard style by default.

You can rely on the default Mapbox Standard style, load the style when you first initialize the map by including it in the style property of Map options, or at any time after the map has been initialized using Map setStyle method by providing a corresponding style URL.

Mapbox Standard

Mapbox Standard is the default style, and instantiating a Map without specifying any style means your map will use Mapbox Standard.

const map = new mapboxgl.Map({
container: 'map',
center: [-74.5, 40],
zoom: 9
});

Classic style templates and custom styles

If you don’t use Mapbox Standard, you can load your style by setting the style property with your custom style URL.

const map = new mapboxgl.Map({
container: 'map',
style: '<STYLE_URL>',
center: [-74.5, 40],
zoom: 9
});

To use one of the Mapbox-owned styles, use one of the following values:

  • mapbox://styles/mapbox/standard
  • mapbox://styles/mapbox/standard-satellite
  • mapbox://styles/mapbox/streets-v12
  • mapbox://styles/mapbox/outdoors-v12
  • mapbox://styles/mapbox/light-v11
  • mapbox://styles/mapbox/dark-v11
  • mapbox://styles/mapbox/satellite-v9
  • mapbox://styles/mapbox/satellite-streets-v12
  • mapbox://styles/mapbox/navigation-day-v1
  • mapbox://styles/mapbox/navigation-night-v1
Use style JSON

Though less common, you can also use a JSON value instead of a URL to load a style if you've written your style JSON manually.

Switch styles at runtime

You can also change the style any time after initializing the map using the Map setStyle method. If you added any layers at runtime, you will need to re-add layers after the new style is loaded.

Configure a style

Depending on what map style you choose, you have different configuration options available to customize aspects of your style such as fonts, colors, and more.

Mapbox Standard

The underlying design paradigm to Mapbox Standard is different from what you know from the classic styles templates. We’re establishing the concept of a basemap; Mapbox Standard is the first Style to follow this paradigm. You can consider everything that is maintained by Mapbox (natural features, roads, buildings etc.) as the basemap into which you embed your custom layers. The difference between the basemap and custom layers is important because different styling rules apply to them.

To change the visual appearance of the Standard basemap, you need to use the setConfigProperty method. Mapbox Standard offers 15 configuration properties that can be used to change the appearance of the basemap using setConfigProperty:

PropertyTypeDescription
showPedestrianRoadsBoolShows or hides all pedestrian roads, paths, trails.
showPlaceLabelsBoolShows or hides place label layers.
showPointOfInterestLabelsBoolShows or hides all POI icons and text.
showRoadLabelsBoolShows or hides all road labels, including road shields.
showTransitLabelsBoolShows or hides all transit icons and text.
show3dObjectsBoolShows or hides all 3d layers (3D buildings, landmarks, trees, etc.) including shadows, ambient occlusion, and flood lights. Important: configuration available starting from v11.5.2 SDK
themeStringSwitches between 4 themes: default, faded, monochrome & custom. Important: configuration available starting from v11.5.2 SDK
theme-dataStringLUT image encoded in Base64 to create a custom color theme. Important: configuration available starting from v11.9.0 SDK
lightPresetStringSwitches between 4 time-of-day states: dusk, dawn, day, and night.
Lights can also be fully customized beyond the presets using the Mapbox style specification.
fontStringDefines font family for the style from predefined options. Options: Alegreya, Alegreya SC, Asap, Barlow, DIN Pro, EB Garamond, Faustina, Frank Ruhl Libre, Heebo, Inter, League Mono, Montserrat, Poppins, Raleway, Roboto, Roboto Mono, Rubik, Source, Code Pro, Spectral, Ubuntu, Noto Sans CJK JP, Open Sans, Manrope, Source Sans Pro, Lato
colorPlaceLabelHighlightColorPlace label color used when setting highlight feature-state. Important: configuration available starting from v11.9.0 SDK
colorPlaceLabelSelectColorPlace label color used when setting select feature-state. Important: configuration available starting from v11.9.0 SDK
colorMotorwaysColorColor override for Motorways.
colorTrunksColorColor override for Trunk Roads.
colorMotorwaysColorColor override for all other roads.

Here’s an example illustrating how to switch the 3D lights in the basemap from the default preset, day, to another preset, dusk.

map.on('style.load', () => {
map.setConfigProperty('basemap', 'lightPreset', 'dusk');
});

Similarly, you can set other configuration properties of the Standard style such as showing POIs, place labels, or specific fonts:

map.on('style.load', () => {
map.setConfigProperty('basemap', 'showPointOfInterestLabels', false);
});

Other options to customize your map using Mapbox Standard include configuring root properties or styling your custom data in custom layers such that it reflects your personal preferences. Note that all the configurations are also available in the Mapbox Studio.

For custom layers that you add to the Mapbox Standard basemap, all configuration options are defined in the Mapbox Style Specification.

EXAMPLE
setConfigProperty example

Use different configuration properties with Mapbox Standard Style.

Style imports

To work with styles like Mapbox Standard, we've introduced Style APIs that allow you to import other styles into the main style you display to your users. These styles will be imported by reference, so updates to them will be reflected in your main style without additional work needed on your side. For example, imagine you have style A and style B. The Style API will allow you to import A into B. Upon importing, you can set configurations that apply to A and adjust them at runtime. The configuration properties for the imported style A will depend on what the creator of style A chooses to be configurable. For the Standard style, 6 configuration properties are available for setting lighting, fonts, and label display options. To import a style, you need to add an imports property to your Style JSON. In the above example, you would add "imports" to your Style JSON for B to import style A and set various configurations as defined in style A in the schema root property.

...
"imports": [
{
"id": "A",
"url": "STYLE_URL_FOR_A",
"config": {
"font": "Montserrat",
"lightPreset": "dusk",
"showPointOfInterestLabels": true,
"showTransitLabels": false,
"showPlaceLabels": true,
"showRoadLabels": false
}
}
],
...

Mapbox Standard Satellite

The Standard Satellite Style (mapbox://styles/mapbox/standard-satellite) combines updated satellite imagery and vector layers to offer users improved clarity and detail. Like Standard style, the Satellite Style receives all updates automatically and also supports light presets. Additionally, it introduces two new configurations showRoadsAndTransit and showPedestrianRoads. Users can now choose to hide roads, simplifying the map style for a better focus on specific areas or features.

The Standard Satellite style offers 13 configuration properties for developers to change when they import it into their own style:

PropertyTypeDescription
showRoadsAndTransitBoolShows or hides all roads and transit networks.
showPedestrianRoadsBoolShows or hides all pedestrian roads, paths, trails.
showPlaceLabelsBoolShows or hides place label layers.
showRoadLabelsBoolShows or hides all road labels, including road shields.
showPointOfInterestLabelsBoolShows or hides all POI icons and text.
showTransitLabelsBoolShows or hides all transit icons and text.
lightPresetStringSwitches between 4 time-of-day states: dusk, dawn, day, and night.
fontStringDefines font family for the style from predefined options.
colorPlaceLabelHighlightColorPlace label color used when setting highlight feature-state. Important: configuration available starting from v11.9.0 SDK
colorPlaceLabelSelectColorPlace label color used when setting select feature-state. Important: configuration available starting from v11.9.0 SDK
colorMotorwaysColorColor override for Motorways.
colorTrunksColorColor override for Trunk Roads.
colorMotorwaysColorColor override for all other roads.

Important: Standard satellite style doesn't support theme and show3dObjects configuration.

Adding interactivity to Standard

You can use Interactions to retrieve basemap attributes and interact with individual features in POI Label, Place Label and building layers in the basemap.

Featuresets describe a collection of layers that can be interacted with in the Standard style, by setting feature-states to change their appearance when interacted with, or to query feature attributes. The following interactions have been added:

  • poi

    • hide feature-state: boolean, when true hides the icon and text. Use this state when displaying a custom annotation in place of the hidden symbol.
  • place-labels

    • hide feature-state: boolean, when true hides the label. Use this state when displaying a custom annotation in place of the hidden symbol.
    • highlight feature-state: boolean, when true, the feature is highlighted. Use this state to create a temporary effect (for example hover).
    • Use colorPlaceLabelHighlight to set a custom highlight color.
    • select feature-state: boolean, when true the feature is selected. Use this state to create an effect that persists until another state is selected. Note: the select state has a higher priority than highlight.
    • Use colorPlaceLabelSelect to set a custom select color.

You can see select & highlight in action in this demo page.

Properties available for features returned by each Featureset:

  • poi
    • name - Name of the point of interest.
    • class - A broad point of interest category, for example 'food_and_drink'.
    • maki - An icon identifier, designed to assign icons using the Maki icon project or other icons that follow the same naming scheme.
    • group - A high-level point of interest category like airport, transit, etc.
    • Available for features with group = transit-label
      • transit_mode - Mode of transport served by a stop/station.
      • transit_stop_type - A type of transit stop.
      • transit_network - A rail station network identifier that is part of specific local or regional transit systems.
    • Available for features with group = airport-label
      • airport_ref - A short identifier code of the airport.
  • place-labels
    • name - Name of the place label.
    • class - Provides a broad distinction between place types.
  • buildings
    • group - A high-level building group like building-2d, building-3d, etc.

Classic style templates and custom styles

The configuration options for classic style templates and custom styles are defined in the Mapbox Style Specification. Note that all the configurations are also available in the Mapbox Studio.

Work with layers

You can use Mapbox GL JS API to add more styled data to the map at runtime. There are two key concepts to understand when preparing to add a layer to a style at runtime: layers and sources. Sources contain geographic data. They determine the shape of the features you’re adding to the map and where in the world they belong. Layers contain styling information. They determine how the data in a source should look on the map.

A layer is a styled representation of data of a single type (for example polygons, lines, or points) that make up a map style. For example, roads, city labels, and rivers would be three separate layers in a map. There are several layer types (for example fill, line, and symbol). You can read more about layers in the Mapbox Style Specification.

Most layers also require a source. The source provides map data that Mapbox GL JS can use with a style document to render a visual representation of that data. There are several source types (for example vector tilesets, GeoJSON, and raster data). You can read more about sources in the Mapbox Style Specification.

In Mapbox GL JS, the Map class exposes the entry point for all methods related to the style object including sources and layers.

Add a layer at runtime

To add a new layer to the map at runtime, start by adding a source using the Style’s addSource method. It is important that you add the source for a new layer after the map has loaded but before attempting to add the layer itself because the source is a required parameter for most layer types.

Then, you’ll use the addLayer method to add the layer to the style. When adding the style layer, you will specify:

  • A unique id that you assign to the new layer
  • The layer type (for example fill, line, or symbol)
  • What data to use by referencing a source
  • The appearance of the data by setting various properties (for example color, opacity, and language)

The sample code below illustrates how to add a GeoJSON source and then add and style a line layer that uses the data in that source.

map.on('style.load', () => {
map.addSource('route', {
type: 'geojson',
data: {
/* ... GeoJSON data ... */
}
});
map.addLayer({
id: 'route',
type: 'line',
source: 'route',
paint: {
'line-color': '#888',
'line-width': 8
}
});
});

The exact available properties available when adding a source and layer varies by source type and layer type. Read more about source types and layer types below.

Update a layer at runtime

You can also update the style of any layer at runtime using the layer's unique layer ID and defining style properties. The sample code below illustrates how to get an existing layer by referencing a layer ID and updating the line-opacity value.

map.setPaintProperty('route', 'line-opacity', 0.9);

The exact available properties available when updating a layer varies by layer type. Read more about layer types below.

Specify order of a layer at runtime for Mapbox Standard

Mapbox Standard and Standard Satellite uses slots to specify where custom data layers can be added. Slots are predetermined locations in the Standard basemap where your layer can be inserted. To add custom layers in the appropriate location in the Standard basemap layer stack, Standard offers 3 carefully designed slots that you can leverage to place your layer. These slots will stay stable, and you can be sure that your own map won't break even as the basemap updates over time.

SlotDescription
bottomAbove polygons (land, landuse, water, etc.)
middleAbove lines (roads, etc.) and behind 3D buildings
topAbove POI labels and behind Place and Transit labels
not specifiedAbove all existing layers in the style

Here’s an example of how to assign a slot to a layer:

map.addLayer({ type: 'line', slot: 'middle' /* ... */ });

Make sure to use slot instead of layer id when inserting a custom layer into the Standard basemap. Layers within the same slot can be rearranged using the optional beforeId argument. This argument specifies the ID of an existing layer before which the new layer will be inserted, causing the new layer to appear visually underneath the specified layer. But, if the layers are in different slots, the beforeId argument is ignored, and the new layer is added to the end of the layers array.

Slots and performance-optimized layers reordering

During 3D globe and terrain rendering, GL JS aims to batch multiple layers together for optimal performance. This process might lead to a rearrangement of layers. Layers draped over globe and terrain, such as fill, line, background, hillshade, and raster, are rendered first. These layers are rendered underneath symbols, regardless of whether they are placed in the middle or top slots or without a designated slot.

EXAMPLE
Layer slot example

Add a new layer to a slot in the Mapbox Standard Style.

Specify order of a layer at runtime for other styles

Map styles contain many individual layers (for example roads, buildings, labels, and more). By default, when you add a new layer to the style, it is placed on top of all the other layers. You can specify where the new layer is positioned relative to existing layers with an additional argument to the addLayer method which specifies an existing layer below which the new one should go.

map.addLayer({ type: 'line' /* ... */ }, 'state-labels');

Remove a layer at runtime

You can remove a layer from a style using Style's removeLayer method.

map.removeLayer('route');

Source types

Vector

A vector source, VectorTileSource, is a vector tileset that conforms to the Mapbox Vector Tile format. A vector source contains geographic features (and their data properties) that have already been tiled. Learn more about the benefits of vector tilesets and how they work in the Vector tiles documentation. For vector tiles hosted by Mapbox, the "url" value should be of the form of mapbox://username.tilesetid.

map.addSource('terrain', {
type: 'vector',
url: 'mapbox://mapbox.mapbox-terrain-v2'
});
Note

All style layers that use a vector source must specify a "source-layer" value.

GeoJSON

A GeoJSON source, GeoJSONSource, is data in the form of a JSON object that conforms to the GeoJSON specification. A GeoJSON source is a collection of one or more geographic features, which may be points, lines, and polygons. Data must be provided via a "data" property, whose value can be a URL or inline GeoJSON.

map.addSource('polygon', {
type: 'geojson',
data: { type: 'Feature', geometry: { type: 'Polygon' /* ... */ } }
});
Note

See the format of the data used in the sample code above in the GeoJSON polygon example.

Raster

A raster source, RasterTileSource, is a raster tileset. For raster tiles hosted by Mapbox, the "url" value should be of the form mapbox://tilesetid.

map.addSource('openstreetmap', {
type: 'raster',
tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
tileSize: 256,
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
});

Raster DEM

A raster DEM source, which is a special case of RasterTileSource, contains elevation data and refers to Mapbox Terrain-DEM (mapbox://mapbox.mapbox-terrain-dem-v1), which is the only supported raster DEM source. It must be added with the type: "raster-dem.

map.addSource('dem', {
type: 'raster-dem',
url: 'mapbox://mapbox.mapbox-terrain-dem-v1'
});

Image

An image source, ImageSource, is an image that you supply along with geographic coordinates. Specify geographic coordinates in the "coordinates" array as [longitude, latitude] pairs so the map knows at what location in the world to place the image. Each coordinate pair in the "coordinates" array represents the image corners listed in clockwise order: top left, top right, bottom right, bottom left.

map.addSource('radar', {
type: 'image',
url: '/mapbox-gl-js/assets/radar.gif',
coordinates: [
[-80.425, 46.437],
[-71.516, 46.437],
[-71.516, 37.936],
[-80.425, 37.936]
]
});

Layer types

Fill layer

A fill style layer renders one or more filled (and optionally stroked) polygons on a map. You can use a fill layer to configure the visual appearance of polygon or multipolygon features.

To add a fill layer, you need to first add a vector or GeoJSON source that contains polygon data. Then you can use the available properties in fill layer to customize its appearance (for example, the color, opacity, or pattern).

map.addLayer({
id: 'maine',
type: 'fill',
source: 'maine',
paint: {
'fill-color': '#0080ff',
'fill-opacity': 0.5
}
});
EXAMPLE
Fill layer example

Add a polygon to a map with an optional stroked border using a GeoJSON source.

Line layer

A line style layer renders one or more stroked polylines on the map. You can use a line layer to configure the visual appearance of polyline or multipolyline features.

To add a line layer, you need to first add a vector or GeoJSON source that contains line data. Then you can use the available properties in line layer to customize the appearance of the layer (for example, the color, width, or dash pattern).

map.addLayer({
id: 'route',
type: 'line',
source: 'route',
layout: {
'line-cap': 'round'
},
paint: {
'line-color': 'red',
'line-opacity': 0.8
}
});
EXAMPLE
Line layer example

Add a line to a map using a GeoJSON source.

Symbol layer

A symbol style layer renders icon and text labels at points or along lines on a map. You can use a symbol layer to configure the visual appearance of labels for features in vector tiles.

To add a symbol layer, you need to first add a vector or GeoJSON source that contains point data. If you want to use icons in this layer, you also need to add images to the style before adding the layer. Then you can use the available properties in symbol layer to customize the appearance of the layer.

map.addLayer({
id: 'city-label',
type: 'symbol',
source: 'labels',
layout: {
'text-field': ['get', 'city_name'],
'text-size': 12
}
});
EXAMPLE
Symbol layer example

Add labels with variable label placement to a map using a GeoJSON source.

Circle layer

A circle style layer renders one or more filled circles on a map. You can use a circle layer to configure the visual appearance of point or point collection features in vector tiles. A circle layer renders circles whose radii are measured in screen units.

To add a circle layer, you need to first add a vector or GeoJSON source that contains point data. Then you can use the available properties in circle layer to customize the appearance of the layer (for example, radius, color, or offset).

map.addLayer({
id: 'park-volcanoes',
type: 'circle',
source: 'national-park',
paint: {
'circle-radius': 6,
'circle-color': '#B42222'
}
});
EXAMPLE
Circle layer example

Style circles with a data-driven property.

Fill extrusion layer

A fill-extrusion style layer renders one or more filled (and optionally stroked) extruded (3D) polygons on a map. You can use a fill-extrusion layer to configure the extrusion and visual appearance of polygon or multipolygon features.

To add a fill extrusion layer, you need to first add a vector or GeoJSON source that contains polygon data. Often you will want the data to contain a data property that you will use to determine the height of extrusion of each feature. This may be a physical height in meters or a way to illustrate a non-physical attribute of the area like population in Census blocks. Once you've added an appropriate source, you can use the available properties in fill-extrusion layer class to customize the appearance of the layer (for example, the height, opacity, or color).

map.addLayer({
id: '3d-buildings',
source: 'composite',
'source-layer': 'building',
filter: ['==', 'extrude', 'true'],
type: 'fill-extrusion',
paint: {
'fill-extrusion-color': '#aaa',
'fill-extrusion-height': ['get', 'height'],
'fill-extrusion-base': ['get', 'min_height'],
'fill-extrusion-opacity': 0.6
}
});
EXAMPLE
Fill extrusion layer example

Display buildings in 3D using a fill extrusion layer.

Hillshade layer

A hillshade style layer, renders digital elevation model (DEM) data on the client-side.

The implementation only supports sources comprised of Mapbox Terrain RGB or Mapzen Terrarium tiles. Once you've added an appropriate source, you can use the available properties in hillshade layer to customize the appearance of the layer.

map.addSource('dem', {
type: 'raster-dem',
url: 'mapbox://mapbox.mapbox-terrain-dem-v1'
});
map.addLayer({
id: 'hillshading',
source: 'dem',
type: 'hillshade'
});
EXAMPLE
Hillshade layer example

Add hillshading using Mapbox terrain DEM source.

Heatmap layer

A heatmap style layer renders a range of colors to represent the density of points in an area.

To add a heatmap layer, you need to first add a vector or GeoJSON source that contains point data. Then you can use the available properties in heatmap layer to customize the appearance of the layer.

map.addLayer({
id: 'earthquakes-heat',
type: 'heatmap',
source: 'earthquakes',
paint: {
'heatmap-color': [
'interpolate',
['linear'],
['heatmap-density'],
0,
'rgba(33,102,172,0)',
0.2,
'rgb(103,169,207)',
0.4,
'rgb(209,229,240)',
0.6,
'rgb(253,219,199)',
0.8,
'rgb(239,138,98)',
1,
'rgb(178,24,43)'
],
'heatmap-radius': 20
}
});
EXAMPLE
Heatmap layer example

Add a heatmap layer using a GeoJSON source with point data.

Raster layer

A raster style layer, renders raster tiles on a map. You can use a raster layer to configure the color parameters of raster tiles.

To add a raster layer, you need to first add a raster source. Then you can use the available properties in raster layer to customize the appearance of the layer.

map.addLayer({
id: 'radar-layer',
type: 'raster',
source: 'radar',
paint: {
'raster-fade-duration': 0
}
});
EXAMPLE
Raster layer example

Add a raster image to a map using an image source and a raster layer.

Background layer

The background style layer, covers the entire map. Use a background style layer to configure a color or pattern to show below all other map content. If the background layer is transparent or omitted from the style, any part of the map view that does not show another style layer is transparent.

You can use the available properties in background layer to customize the appearance of the layer.

map.addLayer({
type: 'background',
paint: {
'background-color': 'blue',
'background-opacity': 0.3
}
});

Styling your layers

Work with expressions

In Mapbox GL JS, you can specify the value for any layout property, paint property, or filter as an expression. Expressions define how one or more feature property value or the current zoom level are combined using logical, mathematical, string, or color operations to produce the appropriate style property value or filter decision.

A property expression is any expression defined using a reference to feature property data. Property expressions allow the appearance of a feature to change with its properties. They can be used to visually differentiate types of features within the same layer or create data visualizations.

A camera expression is any expression defined using ['zoom']. Such expressions allow the appearance of a layer to change with the map’s zoom level. Zoom expressions can be used to create the illusion of depth and control data density.

There are countless ways to apply property expressions to your application, including:

  • Data-driven styling: Specify style rules based on one or more data attribute.
  • Arithmetic: Do arithmetic on source data, for example performing calculations to convert units.
  • Conditional logic: Use if-then logic, for example to decide exactly what text to display for a label based on which properties are available in the feature or even the length of the name.
  • String manipulation: Take control over label text with things like uppercase, lowercase, and title case transforms without having to edit, re-prepare and re-upload your data.
RELATED
Mapbox Style Specification: Expressions

An expression defines a formula for computing the value of the property using the operators described in this section.

Expression syntax

The Mapbox GL JS expressions follow this format:

["expression_name", argument_0, argument_1]

The expression_name is the expression operator, for example, you would use "*" to multiply two arguments or case to create conditional logic.

The arguments are either literal (numbers, strings, or boolean values) or else themselves expressions. The number of arguments varies based on the expression.

Here's one example using an expression to calculate an arithmetic expression (π * 32):

["*", ["pi"], ["^", 3, 2]]

This example uses the "*" operator to multiply two arguments. The first argument is pi, which is an expression that returns the mathematical constant Pi. The second argument is another expression: a pow expression with two arguments of its own. It will return 32, and the result will be multiplied by π.

Expression types

  • Mathematical operators for performing arithmetic and other operations on numeric values
  • Logical operators for manipulating boolean values and making conditional decisions
  • String operators for manipulating strings
  • Data operators for providing access to the properties of source features
  • Camera operators for providing access to the parameters defining the current map view

Data-driven styling at runtime

You can use expressions to determine the style of features in a layer based on data properties in the source data. For example, if you have a source containing point data from individual responses to the 2010 U.S. Census and each point has an "ethnicity" data property, you can use expressions to specify the color of each circle based on reported ethnicity.

The example below uses the match operator to compare the value of the "ethnicity" data property for each point in the source to several possible values. The first argument of the match expression is the value of the "ethnicity" data property. There are several arguments that specify what to do if the value of the data property matches a given string and a final argument that specifies what to do if the value of the data property does not match any of the strings provided.

To read the values of the "ethnicity" data property, this example uses the get operator with "ethnicity" as the sole argument.

Then, it uses stops for the next several arguments for the match expression. Each stop has two arguments: the first is the value to compare to the value of the "ethnicity" data property and the second is the value that should be applied to the layer's circleColor property if the value of the data property matches the first argument.

The second argument of the stop is a color, which is constructed using the rgb operator.

The final argument of the match expression is a fallback value that should be applied to circle-color if the value of the "ethnicity" data property does not match any of the strings provided.

map.addLayer({
id: 'circle',
type: 'circle',
source: 'census',
paint: {
// match the value of the data property to a specific color
'circle-color': [
'match',
['get', 'ethnicity'],
'White',
'#fbb03b',
'Black',
'#223b53',
'Hispanic',
'#e55e5e',
'Asian',
'#3bb2d0',
/* other */ 'black'
]
}
});
EXAMPLE
Data-driven styling example

Style circles with a data-driven property

Zoom-driven styling at runtime

You can use expressions to determine the style of features in a layer based on the camera position, including the zoom level. For example, if you have dense point data displayed using a circle layer, you may want to adjust the radius of circles based on the zoom level to make the data more readable at low zoom levels.

The example below uses the interpolate operator to produce a continuous, smooth series of values between pairs of input and output values ("stops"). Its first argument sets the interpolation type, the second is the value of the zoom level, and the remaining arguments specify the size of the circle radius that should be applied based on the value of the zoom level.

"Exponential" is one of a few types of interpolation available Mapbox expressions. An expression using the exponential operator has one argument: the base, which controls the rate at which the output increases.

The zoom expression does not require any arguments. It will return the value of the current zoom level of the map.

The remaining arguments of the interpolate expression are stops. They represent points along the exponential curve. When a user is viewing the map at zoom level 12 or below, the circles will have a radius of 2. When viewing it at zoom level 22 and above, the circles will have a radius of 180. For all zoom levels between, the radius will be determined by an exponential function and the value will fall somewhere between 2 and 180.

map.addLayer({
id: 'population',
type: 'circle',
source: 'ethnicity-source',
'source-layer': 'sf2010',
paint: {
'circle-radius': [
// Produce a continuous, smooth series of values
// between pairs of input and output values
'interpolate',
['exponential', 1.75], // Set the interpolation type
['zoom'], // Get current zoom level
// If the map is at zoom level 12 or below, set circle radius to 2
12,
2,
// If the map is at zoom level 22 or above, set circle radius to 180
22,
180
]
}
});
EXAMPLE
Zoom-driven styling example

Change building color based on zoom level

Light-driven styling in Standard

Mapbox Standard uses 3D lighting which affects the entire map, like lighting in the real world. This means that when you switch to dark lights, for example to the “night” preset, your custom layers will also be dark. If you want to change how light affects your custom layer, you will need to configure *-emissive-strength, a property which controls how light is being emitted. *-emissive-strength applies to background, fill, circle, text and line layer types.

Here’s an example how you would set *-emissive-strength for a line layer:

map.addLayer({
id: 'my-line-layer',
source: 'vector-source',
'source-layer': 'road',
paint: {
'line-emissive-strength': 1
}
});

This image illustrates how different line-emissive-strength values are impacting the visual appearance of a line layer:

Was this page helpful?