# Map Expressions

# Table of Contents

# Expression Syntax and Concepts

Any layout property, paint property, or filter value can be specified as an expression.

[expression operator, argument1, argument2, ...]
1

Parameter value types: string, number, boolean, or another expression array, null.

Expressions can be nested. Combined expressions example:

// geojson features parameter
"features": [
      {
        "type": "Feature",
        "properties": {
            "id": "1",
            "name":"Point 1",
            "desc":"This is point 1",
            "radius": 10
        },
        "geometry": {
          "type": "Point",
          "coordinates": [
            108.9902114868164,
            34.24813554589752
          ]
        }
      }
]


// Determine circle radius based on radius value in geojson
"circle-radius": [
    "interpolate", ["linear"], ["zoom"],
    // when zoom is 0, radius is the value of radius
    0, ['get','radius'],
    // when zoom is 10, radius is the value of radius; zoom 0-10 increases linearly
    10, ['*', ['get','radius'], 10]
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# Expression Type System

# Overview

Expression input parameter and output result types: boolean, color, string, number, array. From Types in the style specification. Each use of an expression has a known result type and required parameter types. The SDK validates that the expression result type is suitable for the context where it is used. For example, the expression result type in a filter property must be boolean; the + operator parameters must be number.

When using feature data, the SDK typically does not know feature property value types in advance. To maintain type safety, when evaluating data expressions, the SDK checks whether property values are suitable for the context. For example, if you use the expression ["get", "feature-color"] for the circle-color property, the SDK validates that each feature's feature-color value is a string that identifies a valid color. If this check fails, an error is indicated in an SDK-specific way (usually a log message), and the default value for that property is used.

In most cases, this validation occurs automatically where needed. However, in some cases, the SDK may not be able to automatically determine the expected result type of a data expression from the surrounding context. For example, it is unclear whether the expression ["<", ["get", "a"], ["get", "b"]] compares strings or numbers. In such cases, you can use one of the type assertion expression operators to indicate the expected type of the data expression: ["<", ["number", ["get", "a"]], ["number", ["get", "b"]]]. The type assertion checks whether the feature data matches the expected type of the data expression. If this check fails, an error is produced and the entire expression falls back to the default value of the defined property. Assertion operators: array, boolean, number, and string.

Expressions perform only one implicit type conversion: a data expression used in a color context converts the string representation of a color to a color value. In other cases, if you want conversion between types, you must use a type conversion expression operator:

to-boolean: returns boolean
to-number: returns number
to-string: returns string
to-color: returns color
1
2
3
4

For example, if you have a feature property that stores numeric values as strings and you want to use those values as numbers, you can use an expression such as ["to-number", ["get", "property-name"]].

Example of converting string type in data to number type:

// circle-radius expects number value, so string type will cause error

"circle-radius": [
    "interpolate",["linear"],["zoom"],
    0, ['get','radius'],
    10, '*', ["to-number", ["get", "id"]], 10]
]
1
2
3
4
5
6
7

# Assertions

Check whether the input value belongs to a certain type

// Check if input value is an array
["array", value]: returns array

// Check if input value is a boolean
["boolean", value]: returns boolean

// Check if input value is a number
["number", value]: number

// Check if input value is an object
["object", value]: object

// Check if input value is a string
["string", value]: string

// With multiple values above, compare in order until first matching value is returned; if none match, returns false or error

//
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  1. collator

Returns a collator for locale-sensitive comparison operations. case-sensitive and diacritic-sensitive options default to false. The locale parameter specifies the IETF language tag for the locale to use. If not provided, the default locale is used. If the requested locale is unavailable, the collator uses the system-defined fallback locale. Use resolved-locale to test the result of locale fallback behavior.

["collator",
    { "case-sensitive": boolean, "diacritic-sensitive": boolean, "locale": string }
]: collator
1
2
3
  1. literal

Provides a literal array or object value.

["literal", [...] (JSON array literal)]: array<T, N>
["literal", {...} (JSON object literal)]: Object
1
2
  1. format

Returns formatted text containing annotations for mixed-format text-field entries. If set, the text-font parameter overrides the font specified by the root layout property. If set, the font-scale parameter specifies the scale factor relative to the text-size specified in the root layout property.

["format",
    input_1: string, options_1: { "font-scale": number, "text-font": array<string> },
    ...,
    input_n: string, options_n: { "font-scale": number, "text-font": array<string> }
]: formatted
1
2
3
4
5

# Expression Type Conversion

  1. Convert to boolean

Converts input value to boolean. When input is empty string, 0, false, null, or NaN, result is false. Otherwise true.

["to-boolean", value]: boolean
1

If multiple values are provided, each value is evaluated in order until a boolean is obtained. If no input is boolean, the expression is an error.

['boolean', ['feature-state', 'hover'], false]
1

First check if the value of ['feature-state', 'hover'] is boolean; if yes, return that boolean; if no, check the second value in order.

  1. Convert to color

Converts input value to color. If multiple values are provided, each is evaluated in order until the first successful conversion. If no input can be converted, the expression is an error.

["to-color", value, fallback: value, fallback: value, ...]: color
1
  1. Convert to number

Converts input value to number.

  • If input is null or false, result is 0.
  • If input is true, result is 1.
  • If input is string, conversion follows the ECMAScript "String to Number" rules (opens new window).
  • If multiple values are provided, each is evaluated in order until the first successful conversion.
  • If no input can be converted, the expression is an error.
["to-number", value, fallback: value, fallback: value, ...]: number
1
  1. Convert to string

Converts input value to string.

["to-string", value]: string
1
  1. Type check typeof

Returns a string describing the type of the given value.

["typeof", value]: string
1

# Feature data

  1. accumulated

Gets the value of accumulated cluster properties so far. Can only be used in the clusterProperties option of clustered GeoJSON sources.

["accumulated"]: value
1
  1. feature-state

Retrieves property value from the current feature's state. Returns null if the requested property is not on the feature state. Feature state is not part of GeoJSON or vector tile data; it must be set programmatically on each feature. Note that ["feature-state"] can only be used with paint properties that support data-driven styling.

["feature-state", string]: value
1

Retrieves property value from the current feature-state. Returns null if the requested property does not exist on feature-state. feature-state is not part of GeoJSON or vector tile data; it must be set programmatically on each feature. Features are identified by their id property, which must be an integer or string that can be converted to an integer.

Data format example:

{
	"type":"FeatureCollection",
	"features": [
		{
			"type":"Feature",
			"geometry":{
				"type":"Polygon",
				"coordinates":[[[10,20],[10,30],[20,30],[20,10],[10,20]]]
			},
			"properties":{
				"STATE_ID":"54",
				"STATE_NAME":"name"
			},
			"id":54
		},
	]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Note that id is not inside the properties object

'paint': {
	'fill-color': '#627BC1',
	'fill-opacity': [
		'case',
		['boolean', ['feature-state', 'hover'], false],
		1,
		0.5
	]
}
1
2
3
4
5
6
7
8
9
hoveredStateId = e.features[0].id;
map.setFeatureState(
	{ source: 'states', id: hoveredStateId },
	{ hover: false }
);
1
2
3
4
5
  1. geometry-type

Gets the feature's geometry type: (Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon).

["geometry-type"]: string
1

Example:

layout:{
    "text-field": ["geometry-type"]
}
// Returns "Point"
1
2
3
4
  1. id

Gets the feature's ID (if any).

["id"]: value
1
  1. line-progress

Gets progress along a gradient line. Can only be used in the line-gradient property.

["line-progress"]: number
1
  1. properties

Gets the feature properties object. Note that in some cases, directly using ["get", "property_name"] may be more efficient. Example: gets the entire properties object

["properties"]: object
1

# Lookup

  1. at

Retrieves an item from an array. number, whether it's in the array

["at", number, array]: ItemType
1
  1. get

Retrieves property value from the current feature's properties or from another object if a second argument is provided. Returns null if the requested property is missing.

["get", string]: value

["get", string, object]: value
1
2
3
  1. has

Tests whether a property exists in the current feature's properties; if a second argument is provided, tests from another object.

["has", string]: boolean
["has", string, object]: boolean
1
2

Example:

// Check if properties has id property; returns true if yes, false otherwise
filter:["has", 'id']
1
2
  1. length

Gets the length of an array or string.

["length", string | array | value]: number
1

# Decision

Expressions in this section can add conditional logic to styles. For example, the 'case' expression provides basic "if/then/else" logic, and 'match' allows you to map specific values of an input expression to different output expressions.

  1. ! Logical NOT

Logical negation. Returns true if input is false, false if input is true.

["!", boolean]: boolean
1
  1. != Not equal

Returns true if input values are not equal, false otherwise. Comparison is strictly typed: values of different runtime types are always considered unequal. Cases where types are known to differ at parse time are invalid and produce a parse error. Accepts an optional collator parameter for locale-sensitive string comparison.

["!=", value, value]: boolean
["!=", value, value, collator]: boolean
1
2
  1. < Less than

Returns true if the first input is strictly less than the second, false otherwise. Parameters must be string or number. Expression evaluation produces an error if this constraint is not satisfied during evaluation. Cases where this constraint is known not to hold at parse time are invalid and produce a parse error. Accepts an optional collator parameter for locale-sensitive string comparison.

["<", value, value]: boolean
["<", value, value, collator]: boolean
1
2
  1. <= Less than or equal

Similar to < above, equal or less than

["<=", value, value]: boolean
["<=", value, value, collator]: boolean
1
2
  1. == Equal comparison

Comparison is strictly typed; values of different runtime types are always considered unequal.

["==", value, value]: boolean
["==", value, value, collator]: boolean
1
2
  1. > Greater than

Whether the first parameter is greater than the second

[">", value, value]: boolean
[">", value, value, collator]: boolean
1
2
  1. >= Greater than or equal
[">=", value, value]: boolean
[">=", value, value, collator]: boolean
1
2
  1. all All satisfy

Whether all parameters are true; returns true if yes, false if any is not

["all", boolean, boolean]: boolean
["all", boolean, boolean, ...]: boolean
1
2
  1. any Any satisfy

Whether any parameter is true; returns true if yes, false if all are false

["any", boolean, boolean]: boolean
["any", boolean, boolean, ...]: boolean
1
2
  1. case Conditional Result is the output of the first satisfied condition; if none are satisfied, returns fallback.
["case",
    condition1: boolean, output: OutputType,
    condition2: boolean, output: OutputType,
    ...,
    fallback: OutputType
]: OutputType
1
2
3
4
5
6

Example:

"circle-color": [
    "case",
    ['has','ids'], 'red',
    ['has','id'], 'yellow',
    'blue'
],

// Condition return value must be boolean type, equivalent to
"circle-color": [
    "case",
    true, 'red',
    false, 'yellow',
    'blue'
],

// Above means: if satisfied red, if not satisfied yellow, if none satisfied (default) blue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  1. coalesce Coalesce

Evaluates each expression in order until the first non-null value is obtained, then returns that value.

  1. match Match

Selects the output whose label value matches the input; if no match is found, selects the fallback value. Input can be any expression (e.g. ["get", "building_type"]). Each label must be:

  • A single literal value; or
  • An array of literal values, which must be all strings or all numbers (e.g. [100, 101] or ["c", "b"]). If any value in the array matches, the input matches, similar to the deprecated "in" operator.

Each label must be unique. If input type does not match label type, the result will be the fallback value.

["match",
    input: InputType (number or string),
    label: InputType | [InputType, InputType, ...], output: OutputType,
    label: InputType | [InputType, InputType, ...], output: OutputType,
    ...,
    fallback: OutputType
]: OutputType
1
2
3
4
5
6
7

Example:

"circle-color": [
    'match', ['get', 'name'],
    'Point 1', 'red',
    'Point 2', 'yellow',
    ['Point 3','Point 4'], 'blue',
    '#fff'
],

// Get name value from feature's properties, match to corresponding color by name; default (no match) #fff. ['Point 3','Point 4'] means label can be array type.
1
2
3
4
5
6
7
8
9

# Ramps, scales, curves

  1. interpolate Interpolation

Produces continuous, smooth results by interpolating between pairs of input and output values ("stops"). input can be any number expression (e.g. ["get", "population"]). stop_input must be strictly ascending numeric literals. Output type must be number, array<number>, or color.

Interpolation types:

  • ["linear"]: Linearly interpolates between the stop less than the input and the stop greater than the input.
  • ["exponential", base]: Exponentially interpolates between stops less than and greater than the input. base controls the rate of output increase: higher values increase output more toward the high end of the range. Values close to 1 produce near-linear output increase.
  • ["cubic-bezier", x1, y1, x2, y2]: Interpolates using the cubic Bezier curve defined by the given control points.
["interpolate",
    interpolation: ["linear"] | ["exponential", base] | ["cubic-bezier", x1, y1, x2, y2 ],
    input: number,
    stop_input_1: number, stop_output_1: OutputType,
    stop_input_n: number, stop_output_n: OutputType, ...
]: OutputType (number, array<number>, or Color)
1
2
3
4
5
6

Example:

"line-opacity": [
    "interpolate", ["linear"], ["zoom"],
    9, 0.8,
    15, 0.5
]

// When zoom is 9, opacity is 0.8; when zoom is 15, opacity is 0.5
1
2
3
4
5
6
7
  1. interpolate-hcl

Same as above, except output must be hcl color,

["interpolate-hcl",
    interpolation: ["linear"] | ["exponential", base] | ["cubic-bezier", x1, y1, x2, y2 ],
    input: number,
    stop_input_1: number, stop_output_1: Color,
    stop_input_n: number, stop_output_n: Color, ...
]: Color
1
2
3
4
5
6
  1. interpolate-lab

Same as above, except output must be lab color,

["interpolate-lab", interpolation: ["linear"] | ["exponential", base] | ["cubic-bezier", x1, y1, x2, y2 ], input: number, stop_input_1: number, stop_output_1: Color, stop_input_n: number, stop_output_n: Color, ... ]: Color

  1. step

Equivalent to: get the result of input value; if within a certain range, return a result.

Produces discrete stepped results by evaluating a piecewise constant function defined by pairs of input and output values ("stops").

  • input can be any number expression (e.g. ["get", "radius"]).
  • stop_input must be strictly ascending numbers. stop_output is the output value;
  • If input is less than the first stop, returns the first stop_output_0.
["step",
    input: number,
    stop_output_0: OutputType,
    stop_input_1: number, stop_output_1: OutputType,
    stop_input_n: number, stop_output_n: OutputType, ...
]: OutputType

1
2
3
4
5
6
7

Example

"circle-color": [
    // Based on radius value in feature's properties
    'step', ['get', 'radius'],
    // radius < 3 displays #fff
    '#fff',
    // 3-4 displays red
    3, 'red',
    // 5-6 displays yellow
    5, 'yellow',
    // 7+ displays blue
    7, 'blue',
],
1
2
3
4
5
6
7
8
9
10
11
12

# Variable binding

  1. let

Binds an expression to a named variable, which can then be referenced in the result expression using ["var", "variable_name"].

["let",
    string (alphanumeric literal), any, string (alphanumeric literal), any, ...,
    OutputType
]: OutputType
1
2
3
4
  1. var References a variable bound with "let".
["var", previously bound variable name]: the type of the bound expression
1

# String operations

  1. concat String concatenation

Returns string, concatenating each input. Each input is converted to string as if by to-string.

["concat", value, value, ...]: string
1

Example:

"text-field": ['concat' ,'aaa', 'bbb']

Result: aaabbb
1
2
3
  1. downcase To lowercase
["downcase", string]: string
1
  1. upcase To uppercase

Returns the input string converted to uppercase. Follows the Unicode default case conversion algorithm and Unicode character database locale-insensitive case mappings.

["upcase", string]: string
1
  1. is-supported-script Supported script

Returns true if the input string is expected to render clearly. Returns false if the input string contains parts that cannot be rendered without losing meaning.

["is-supported-script", string]: boolean
1
  1. resolved-locale

Returns the IETF language tag of the locale used by the provided collator. Can be used to determine the default system locale or whether the requested locale was successfully loaded.

["resolved-locale", collator]: string
1

# Color expressions

  1. rgb

Creates a color value from red, green, and blue components, which must be between 0 and 255, with alpha component 1. If any component is out of range, the expression is an error.

["rgb", number, number, number]: color
1
  1. rgba

Creates a color value from red, green, and blue components (0-255) and alpha component (0-1). If any component is out of range, the expression is an error.

["rgba", number, number, number, number]: color
1
  1. to-rgba

Returns a four-element array containing the input color's red, green, blue, and alpha components in order.

["to-rgba", color]: array<number, 4>

1
2

# Math expressions

  1. - Subtraction

For two inputs, returns the result of subtracting the second from the first. For a single input, returns the result of subtracting it from 0.

["-", number, number]: number
["-", number]: number
1
2
  1. * Multiplication

Returns the product of the inputs.

["*", number, number, ...]: number
1
  1. / Division

Returns the result of floating-point division of the first input by the second.

["/", number, number]: number
1
  1. % Modulo

Returns the remainder after integer division of the first input by the second.

["%", number, number]: number
1
  1. ^ Power

Returns the result of raising the first input to the power of the second.

["^", number, number]: number
1
  1. + Addition

Returns the sum of the inputs.

["+", number, number, ...]: number
1
  1. abs Absolute value

Returns the absolute value of the input.

["abs", number]: number
1
  1. Trigonometric functions
// 1. Returns the arccosine of the input.
["acos", number]: number

// 2. Returns the arcsine of the input.
["asin", number]: number

// 3. Returns the arctangent of the input.
["atan", number]: number

// 4. Returns the cosine of the input.
["cos", number]: number

// 5. Returns the sine of the input.
["sin", number]: number

// 6. Returns the tangent of the input.
["tan", number]: number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  1. Rounding
// 1. Ceiling: returns the smallest integer greater than or equal to the input.
["ceil", number]: number

// 2. Returns the largest integer less than or equal to the input.
["floor", number]: number

// 3. Round: rounds input to the nearest integer. Halfway values round away from zero. E.g. ["round", -1.5] evaluates to -2.
["round", number]: number
1
2
3
4
5
6
7
8
  1. Constants
// 1. Returns the mathematical constant e.
["e"]: number

// 2. Returns the natural logarithm of the input.
["ln", number]: number

// 3. Returns the mathematical constant ln(2).
["ln2"]: number

// 4. Returns the base-10 logarithm of the input.
["log10", number]: number

// 5. Returns the base-2 logarithm of the input.
["log2", number]: number

// 6. Returns the mathematical constant pi.
["pi"]: number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  1. max Maximum

Returns the maximum of the inputs.

["max", number, number, ...]: number
1
  1. min Minimum

Returns the minimum of the inputs.

["min", number, number, ...]: number
1
  1. sqrt Returns the square root of the input.
["sqrt", number]: number
1

# Zoom

Gets the current zoom level. Note that in style layout and paint properties, ["zoom"] may only appear as input to a top-level "step" or "interpolate" expression.

["zoom"]: number
1

# Heatmap

  1. heatmap-density

Gets the kernel density estimate for pixels in the heatmap layer, a relative measure of how crowded data points are around a specific pixel. Can only be used in the heatmap-color property.

["heatmap-density"]: number
1

heatmap-weight: Indicates a point's contribution to heatmap weight; heatmap should display more prominently where contribution is greater

heatmap-intensity: Heatmap intensity, somewhat similar to heatmap-weight, but this property sets the overall heatmap intensity

heatmap-color: Heatmap color, sets what color corresponds to each heatmap value

heatmap-radius: Radius in pixels for calculating point weight in heatmap, default 30

heatmap-opacity: Heatmap opacity

"heatmap-weight": [
    "interpolate",
    ["linear"],
    ["get", "mag"],
      0, 0,
      6, 1
 ]
1
2
3
4
5
6
7

Gets each feature's mag property value to set each point's contribution to heatmap intensity. Example: when mag is between 0-6, contribution to heatmap intensity is linearly 0 to 1; >6 means contribution 1, <0 means no contribution

"heatmap-intensity": [
    "interpolate",
    ["linear"],
    ["zoom"],
    0, 1,
    9, 3      
]
1
2
3
4
5
6
7

Sets heatmap intensity based on map zoom level. When zoom level changes linearly between 0-9, heatmap intensity changes linearly from 1-3; <0 intensity 0, >9 intensity 3

"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)"
 ]
1
2
3
4
5
6
7
8
9
10
11

Sets heatmap color. Heatmap colors change linearly between given intensity ranges. heatmap-density represents heatmap density.

"heatmap-radius": [
    "interpolate",
    ["linear"],
    ["zoom"],
    0, 2,
    9, 20     
]
1
2
3
4
5
6
7

Changes heatmap calculation radius at different zoom levels,

"heatmap-opacity": [
    "interpolate",
    ["linear"],
    ["zoom"],
    7, 1,
    9, 0    
]
1
2
3
4
5
6
7

Sets heatmap opacity (overall graphic opacity). Gradually fades heatmap between zoom 7-9; fully transparent when zoom > 9

# Other methods

Any layout or paint property value can be specified as a function. Using functions allows map feature appearance to change with current zoom level and/or feature's properties. Default input value is zoom

  1. stops

Must be an array defining the function by input and output value pairs. One input value and one output value is called a "stop". Stop output values must be literal values (not functions or expressions) and must be valid for the property. For example, stop output values used in the fill-color property must be colors.

Example:

"circle-radius": {
    "stops": [
        // when zoom is 1, radius is 2
        [1, 2],
        // when zoom is 10, radius is 20
        [10, 20]
    ]
}


// [10, 20] is a stop: 10 is input value, 20 is output value; multiple stops form stops

1
2
3
4
5
6
7
8
9
10
11
12

Four types of stops

(1) Exponential type: final output value is generated by exponential interpolation within the range between stop difference terms

map.addLayer({
     "paint": {
         "circle-color": {
           // type for exponential can be omitted
         "type": "exponential",
         "property": "val",
         "stops": [
               // when properties.val is 0, circle color is red
               [0, "red"],
              // when properties.val is 500, circle color is green
               [500, "green"],
               // when properties.val is 1000, circle color is blue
               [1000, "blue"]
           ],
           // optional, default: 1. Exponential base for interpolation curve, controls growth rate of final result; higher values produce larger results; when value approaches 1, function uses linear calculation.
           "base": 0.9
       }
   }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

(2) Interval type: final output value is generated by step interpolation within the range between stop difference terms; stop input parameters must be numeric.

map.addLayer({
     "paint": {
         "circle-opacity": {
             "type": "interval",
             "property": "val", // if omitted, will use zoom
             "stops": [
                 // when properties.val >= 0, circle color is red
                 [0, "red"],
                 // when properties.val >= 500, circle color is green
                 [500, "green"],
                 // when properties.val >= 1000, circle color is blue
                 [1000, "blue"],
             ]
         }
     }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

(3) Categorical type: final output value exactly matches the output value corresponding to the stop input value

map.addLayer({
     "paint": {
         "fill-color": {
         "type": "categorical",
         "property": "num", // required
         "stops": [
               // only when properties.num equals 5, fill color is red
               [5, "red"],
               // only when properties.num equals 10, fill color is green
               [10, "green"],
           ]
       }
   }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14

(4) Identity type: final output value exactly equals input value

map.addLayer({
 "paint": {
     "line-color": {
         "type": "identity",
           // line color directly takes properties.color value
         "property": "color"
       }
   }
});
1
2
3
4
5
6
7
8
9
  1. property

A string representing the property name. If specified, the function uses the specified feature property as input.

 "circle-radius": {
    "property": "radius",
    "stops": [
        // when radius is 1, radius is 2
        [1, 2],
        // when radius is 5, radius is 20
        [5, 20],
        // when radius is 10, radius is 5
        [10, 5]
    ]
}

// Here 1 5 10 are radius value steps; in range 1-5, value is 2-20,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  1. base Type is number, default is 1. Exponential base for the interpolation curve. Controls the rate of increase of function output. Higher values increase output more toward the high end. Output increases linearly when value is close to 1. Adjusts linearity
 "circle-radius": {
    "base": 1.3,
    "stops": [
        // when radius is 1, radius is 2
        [1, 2],
        // when radius is 5, radius is 20
        [10, 20],
    ]
}

// base 1 is normal display; <1 e.g. 0.8 reduces difference; >1 increases difference, larger gets larger, smaller gets smaller.

1
2
3
4
5
6
7
8
9
10
11
12
  1. type

Optional values: "identity", "exponential","interval", or "categorical"

  • identity: Function that returns its input as output.
  • exponential: Function that generates output by interpolating between stops less than and greater than the function input. Domain (input values) must be numeric, and the style property must support interpolation. Style properties that support interpolation are marked with the "exponential" symbol, and exponential is the default function type for these properties.
  • interval: Function that returns the stop output value just less than the function input. Domain (input values) must be numeric. Any style property can use interval functions. For properties marked with the "interval" symbol, this is the default function type. *categorical: Function whose returned stop value equals the function input value.
  1. default

Value used as fallback when no other value is available. Used in these cases:

  • In categorical functions, when feature value does not match any stops value.
  • In property and zoom-and-property functions, when the feature does not contain the specified property value.
  • In identity functions, when the feature value is invalid for the style property (e.g. if the function is used for circle-color property but feature property value is not a string or invalid color).
  • In interval or exponential property and zoom-and-property functions, when feature value is not numeric. If no default is provided, the style property default is used in these cases.
  1. colorSpace

Optional values: "rgb", "lab", "hcl".

Color space for interpolating colors. Compared to interpolating colors in RGB space, interpolating in perceptual color spaces like LAB and HCL tends to produce more consistent-looking color bands and more distinguishable colors.

  • "rgb": Interpolate color values in RGB color space
  • "lab": Interpolate color values in LAB color space.
  • "hcl": Interpolate color values in HCL color space, interpolating Hue, Chroma, and Luminance channels separately.
  1. Zoom-and-property functions

Allows map feature appearance to change with both its properties and zoom. Each stop is an array of two elements: the first is an object with property input value and zoom, the second is the function output value. Note that support for property functions is not yet complete.

{
    "circle-radius": {
        "property": "rating",
        "stops": [
            // zoom is 0 and "rating" is 0 -> circle radius will be 0px
            [{zoom: 0, value: 0}, 0],

            // zoom is 0 and "rating" is 5 -> circle radius will be 5px
            [{zoom: 0, value: 5}, 5],

            // zoom is 20 and "rating" is 0 -> circle radius will be 0px
            [{zoom: 20, value: 0}, 0],

            // zoom is 20 and "rating" is 5 -> circle radius will be 20px
            [{zoom: 20, value: 5}, 20]
        ]
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Usage examples

// match
// match is commonly used for enum field rendering, e.g. unique value rendering.

'circle-color': [
    'match',
    ['get', 'type'],
    1, '#FFD273',
    2, '#E86D68',
    '#A880FF'
]

// case 
// case is commonly used for segmented numeric field rendering; value range is [inclusive, exclusive), e.g. classified rendering.

'circle-color': [
    'case',
    ['<', ['get', 'speed'], 10.8], 'rgba(0,0,0,0)', //<10.8
    ['<', ['get', 'speed'], 17.2], 'rgba(153, 255, 153, .9)', //>=10.8 & <17.2
    ['<', ['get', 'speed'], 24.5], 'rgba(102, 204, 255, .9)',
    ['<', ['get', 'speed'], 32.7], 'rgba(255, 255, 102, .9)',
    ['<=', ['get', 'speed'], 41.5], 'rgba(253, 139, 0, .9)',
    ['<=', ['get', 'speed'], 50.1], 'rgba(255, 51, 0, .9)', //>=41.5 & <50.1
    'rgba(255, 0, 255, .9)' // default, >=50.1
]
// Note:
// First condition uses <;
// Middle conditions use >= and <;
// Last condition uses >=;

// step
// step is similar to case above, but value range is (exclusive, inclusive].

// <=100, 100-500, >500
"circle-color": [
    "step",
    ["get", "count"],
    "#51bbd6", 100,
    "#f1f075", 500,
    "#f28cb1" // other
]

'circle-color': [
    'step',
    ['to-number', ['get', 'CID']],
    '#0098A3',  10,
    '#00CA8D', 20,
    '#37C508', 30,
    '#98F300',  40,
    '#EFFF85'
]

// interpolate
// interpolate can achieve proportional interpolation rendering.

// <=8, 8-10, >10
"background-color": [
    "interpolate",
    ["linear"],
    ["zoom"],
    8, "rgba(0, 0, 255, 0.2)",
    10, "rgba(255, 0, 0, 0.2)"
]

// <=20, 20-60, 60-100, >100
'fill-extrusion-color': [
    'interpolate',
    ['linear'],
    ['get', 'height'],
    20, 'rgba(255,255,191, 0.65)',
    60, 'rgba(253,174,97, 0.65)',
    100, "rgba(215,25,28, 0.65)"
]

// exponential
"fill-opacity": [
    "interpolate",
    ["exponential", 1.5],
    ["zoom"],
    2, 0.3,
    7, 0
]
// Note:

// zoom is a special character for map zoom level; similarly geometry-type refers to geom type.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

# Expressions for filter

{
    paint:{
        ...
    }   
    filter: ['in','radius',5]
}

1
2
3
4
5
6
7
  1. Property existence
["has", key] feature[key] exists
["!has", key] feature[key] does not exist
1
2
  1. Comparison filters
["==", key, value] equal: feature[key] = value
["!=", key, value] not equal: feature[key] ≠ value
[">", key, value] greater than: feature[key] > value
[">=", key, value] greater than or equal: feature[key] ≥ value
["<", key, value] less than: feature[key] < value
["<=", key, value] less than or equal: feature[key] ≤ value
1
2
3
4
5
6
  1. in
["in", key, v0, ..., vn] set contains: feature[key]{ v0,...,vn }
["!in", key, v0, ..., vn] set excludes: feature[key]{ v0,...,vn }
1
2
  1. Combined filters

["all", f0, ..., fn] logical AND: F0 ∧...∧ FN ["any", f0, ..., fn] logical OR: F0 ∨...∨ FN ["none", f0, ..., fn] logical NOR: ¬ F0 ∧...∧¬ FN

In the above four categories:

key must be a feature property or one of these special values:

  • "$type": feature type. Can be used with "==","!=", "in", and "!in". Result may be "Point", "LineString", or "Polygon".
  • "$id": feature identifier. This key can be used with "==", "!=", "has", "!has", "in", and "!in".
{
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "properties": {
            "id": "1",
            "name":"Point 1",
            "desc":"This is point 1",
            "radius": 1
        },
        "id":54, // $id is here
        "geometry": {
          "type": "Point",  // $type is here
          "coordinates": [
            108.9902114868164,
            34.24813554589752
          ]
        }
      }
    ]
}    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

value must be a string, number, or boolean for comparison.

Usage examples

// == and != can filter layer display by field. E.g.: only show Changping district on map, or show all regions except Changping.

// Only show Changping district on map
var filter = ['==', 'name', 'Changping District'];

// Show all regions except Changping on map
var filter = ['!=', 'name', 'Changping District'];


// >, >=, <, <= filter layers by comparison, so the field must be numeric or converted via to-number. E.g.: show regions where count>=10.

var filter = ['>=', 'count', 10];

// in and match can both filter layers by field for multiple values. E.g.: show Changping and Haidian districts on map.

// in
var filter = [
    'in',
    'name',
    'Changping District',
    'Haidian District'
];
// match
var filter = [
    "match",
    [
        "get",
        "name"
    ],
    [
        "Changping District",
        "Haidian District",
    ],
    true,
    false
]

// Following the above example, to show all regions except Haidian and Changping, we can use !in or swap match conditions:

// in 
var filter = [
    '!in',
    'name',
    'Changping District',
    'Haidian District'
];
// match
var filter = [
    "match",
    [
        "get",
        "name"
    ],
    [
        "Changping District",
        "Haidian District",
    ],
    false,
    true
]

// Multiple conditions
// Sometimes we need multi-condition filtering, e.g.: type==1 and count>10:

var filter = [
    'all',
    ['>=', 'count', 10],
    ['==', 'type', 1]
]

// Sometimes we filter by geometry type:

var filter = [
    "==",
    ["geometry-type"],
    "LineString"
];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

Expression reference

# I. Math operators

# II. Logical operators

# III. String operators

# IV. Data operators

Data expressions access data, e.g. ['get','name'] gets the name value from data

# V. Camera operators

Camera expressions can change based on map zoom value.

Example:

{
    "circle-radius": [
        "interpolate", ["linear"], ["zoom"],
        // zoom is 5 or less -> circle radius is 1px
        5, 1,
        // zoom is 10 or greater -> circle radius is 5px
        10, 5
    ]
}
1
2
3
4
5
6
7
8
9