Expressions form a little language that can be used to compute values for various layer properties.
It is recommended to import them in the following fashion:
import Mapbox.Expression as E exposing (Expression, CameraExpression, DataExpression, str, float, int, true, false)This way you can use the language without much syntactic fuss and you have easy access to the literals.
You'd like to adjust font size of a town based on the number of people who live there. In plain Elm, you might wright the following function:
sizeByPopulation : Dict String Int -> Int
sizeByPopulation properties =
Dict.get "population" properties
|> Maybe.withDefault 1000
|> scale ( 0, 1000 ) ( 9, 20 )In the expression language you can do this in a similar fassion:
sizeByPopulation : Expression DataExpression Float
sizeByPopulation =
E.getProperty "population"
|> E.toFloat 1000
|> E.interpolate E.Linear
[ ( 0, int 9 )
, ( 1000, int 20 )
]Note: If you are familiar with the JS version of the style spec, we have made a few changes. Argument order has been switched for many functions to support using pipeline style more naturally. Some functions use overloading in the original, these have been renamed to not be overloaded. Finally, we have chosen not to represent some parts of the spec that are superflous (especially when used from Elm), namely functions and let-in expressions.
A data expression is any expression that access feature data -- that is, any expression that uses one of the data operators: getProperty, hasProperty , id, geometryType, or properties. Data expressions allow a feature's properties to determine its appearance. They can be used to differentiate features within the same layer and to create data visualizations.
makeRGBColor
-- red is higher when feature.properties.temperature is higher
(getProperty "temperature")
-- green is always zero
(int 0)
-- blue is higher when feature.properties.temperature is lower
(getProperty "temperature" |> minus 100)
|> Layer.circleColorThis example uses the getProperty operator to obtain the temperature value of each feature. That value is used to compute arguments to the makeRGBColor operator, defining a color in terms of its red, green, and blue components.
A camera expression is any expression that uses the zoom operator. Such expressions allow the the appearance of a layer to change with the map's zoom level. Camera expressions can be used to create the appearance of depth and to control data density.
zoom
|> interpolate Linear
[ ( 5, int 1 )
, ( 10, int 5 )
]
|> Layer.circleRadiusThis example uses the interpolate operator to define a linear relationship between zoom level and circle size using a set of input-output pairs. In this case, the expression indicates that the circle radius should be 1 pixel when the zoom level is 5 or below, and 5 pixels when the zoom is 10 or above. In between, the radius will be linearly interpolated between 1 and 5 pixels
Camera expressions are allowed anywhere an expression may be used. However, when a camera expression used as the value of a layout or paint property, the zoom operator must appear only as the input to an outer interpolate or step expression
There is an important difference between layout and paint properties in the timing of camera expression evaluation. Paint property camera expressions are re-evaluated whenever the zoom level changes, even fractionally. For example, a paint property camera expression will be re-evaluated continuously as the map moves between zoom levels 4.1 and 4.6. On the other hand, a layout property camera expression is evaluated only at integer zoom levels. It will not be re-evaluated as the zoom changes from 4.1 to 4.6 -- only if it goes above 5 or below 4.
Turns an expression into JSON
All of the types used as expression results are phantom (i.e. they don't have any runtime values but are used purely for compile-time checking). As such we use a mix of standard elm types for their familiarty:
FloatStringArrayBoolWe introduce the following types:
Represents a color value
Represents a mixed-type dictionary where keys are always strings
Used for locale sensitive string comparisons.
Represents a richly formatted string.
(And also a bunch of Enum types, that will be documented in the Enums section).
You can use the following functions to transfer Elm values into the Expression language:
Takes a list of key value pairs. The values are JSON Values, therefore allowing for mixed types.
Returns a Collator for use in locale-dependent comparison operations. The first argument specifies if the comparison should be case sensitive. The second specifies if it is diacritic sensitive. The final locale argument specifies the IETF language tag of the locale to use.
Returns a Collator with the default locale (which depends on the system running the code), which is not sensitive to case nor diacritic.
In some cases, you will need to force the type system to cooperate. The following assertions will force the type and cause a run-time error if the type is wrong:
You can also use these functions to explicitly cast to a particular type:
Converts the input value to a boolean. The result is false when then input is an empty string, 0, false, null, or NaN; otherwise it is true.
Converts the input value to a color. If it can't be converted, the falback value will be used.
input
|> toColor (rgba 0 0 0 1) -- fallback colorConverts the input value to a number, if possible. If the input is null or false, the result is 0. If the input is true, the result is 1. If the input is a string, it is converted to a number as specified by the "ToNumber Applied to the String Type" algorithm of the ECMAScript Language Specification. If this fails, the fallback value is used.
input
|> toFloat 0 -- fallbackConverts the input value to a string. If the input is null, the result is "". If the input is a boolean, the result is "true" or "false". If the input is a number, it is converted to a string as specified by the "NumberToString" algorithm of the ECMAScript Language Specification. If the input is a color, it is converted to a string of the form "rgba(r,g,b,a)", where r, g, and b are numerals ranging from 0 to 255, and a ranges from 0 to 1. Otherwise, the input is converted to a string in the format specified by the JSON.stringify function of the ECMAScript Language Specification.
Returns a string describing the type of the given value.
Retrieves an item from an array.
Retrieves a property value from an object. Returns null if the requested property is missing.
Tests for the presence of an property value in an object.
Gets the length of an array.
Gets the length of a string.
Retrieves a property value from the current feature's state. Returns null if the requested property is not present on the feature's state. A feature's state is not part of the GeoJSON or vector tile data, and must be set programmatically on each feature. Note that featureState can only be used with paint properties that support data-driven styling.
Gets the feature's geometry type: Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon.
Gets the feature's id, if it has one.
Gets the feature properties object. Note that in some cases, it may be more efficient to use getProperty (str "property-name") directly.
Retrieves a property value from the current feature's properties. Returns null if the requested property is missing.
Tests for the presence of an property value in the current feature's properties.
The expressions in this section can be used to add conditional logic to your styles.
Returns true if the input values are equal, false otherwise.
Returns true if the input values are not equal, false otherwise.
Returns true if the first input is strictly less than the second, false otherwise.
Returns true if the first input is less than or equal to the second, false otherwise.
Returns true if the first input is strictly greater than the second, false otherwise.
Returns true if the first input is greater than or equal to the second, false otherwise.
Strings can be compared with a collator for locale specific comparisons:
Logical operators:
Logical negation. Returns true if the input is false, and false if the input is true.
Returns true if all the inputs are true, false otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to false, the result is false and no further input expressions are evaluated.
Returns true if any of the inputs are true, false otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to true, the result is true and no further input expressions are evaluated.
Control flow:
The ternary operator:
Layer.iconImage <|
ifElse
(greaterThan (getProperty (str "size")) (float 30))
(str "hospital-32")
(str "clinic-32")Selects the first output whose condition evaluates to true
Selects the output whose label value matches the input value, or the fallback value if no match is found.
getProperty (str "type")
|> matchesStr
[ ("hospital", str "icon-hospital")
, ("clinic", str "icon-medical")
]
(str "icon-generic") -- fallback value
|> Layer.iconImageSelects the output whose label value matches the input value, or the fallback value if no match is found.
getProperty (str "size")
|> matchesStr
[ (1, str "icon-hospital")
, (2, str "icon-medical")
]
(str "icon-generic") -- fallback value
|> Layer.iconImageEvaluates each expression in turn until the first non-null value is obtained, and returns that value.
Produces continuous, smooth results by interpolating between pairs of input and output values ("stops"). The output type must be Float, Array Float, or Color.
zoom
|> interpolate Linear
[ ( 5, int 1 )
, ( 10, int 5 )
]
|> Layer.circleRadiusInterpolation types:
Linear: interpolates linearly between the pair of stops just less than and just greater than the input.Exponential base: interpolates exponentially between the stops just less than and just greater than the input. base controls the rate at which the output increases: higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly.CubicBezier (x1, y1) (x2, y2): interpolates using the cubic bezier curve defined by the given control points.Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of input and output values ("stops"). Stop inputs must be Floats in strictly ascending order. Returns the output value of the stop just less than the input, or the first input if the input is less than the first stop.
zoom
|> step (int 1)
[ ( 5, int 3 )
, ( 10, int 5 )
]
|> Layer.circleRadiusReturns a string consisting of the concatenation of the inputs.
Argument order designed for pipelines:
a |> append b --> a ++ bReturns the input string converted to lowercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.
Returns the input string converted to uppercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database.
Returns true if the input string is expected to render legibly. Returns false if the input string contains sections that cannot be rendered without potential loss of meaning (e.g. Indic scripts that require complex text shaping, or right-to-left scripts if the the mapbox-gl-rtl-text plugin is not in use in Mapbox GL JS).
Returns the IETF language tag of the locale being used by the provided collator. This can be used to determine the default system locale, or to determine if a requested locale was successfully loaded.
Returns formatted text containing annotations for use in mixed-format text-field entries.
Layer.textField <|
E.format
[ E.getProperty (str "name_en")
|> E.formatted
|> E.fontScaledBy (float 1.2)
, E.formatted (str "\n")
, E.getProperty (str "name")
|> E.formatted
|> E.fontScaledBy (float 0.8)
|> E.withFont (E.strings [ "DIN Offc Pro Medium" ])A FormattedText is composed of a list of FormattedString which essentially are a tuple of a string expression and some formatting information that applies to that string.
Takes a String Expression and turns it into a FormattedString with default formatting.
Specifies a scaling factor relative to the text-size specified in the root layout properties.
Note: this is indempotent, so calling str "hi" |> formatted |> fontScaledBy 1.2 |> fontScaledBy 1.2 is equivalent to str "hi" |> formatted |> fontScaledBy 1.2 rather than str "hi" |> formatted |> fontScaledBy 1.44.
Overrides the font specified by the root layout properties.
Creates a color value from red, green, and blue components, which must range between 0 and 255, and an alpha component of 1. If any component is out of range, the expression is an error.
Creates a color value from red, green, blue components, which must range between 0 and 255, and an alpha component which must range between 0 and 1. If any component is out of range, the expression is an error.
Returns a four-element array containing the input color's red, green, blue, and alpha components, in that order.
Returns the result of subtracting the first input from the second.
a |> minus b --> a - bReturns the product of the inputs.
Returns the result of floating point division of the second input by the first.
a |> divideBy b --> a / bReturns the remainder after integer division of the second input by the first.
a |> modBy b --> a % bReturns the sum of the inputs.
Returns the result of raising the second input to the power specified by the first.
a |> raiseBy b --> a ^ bReturns the square root of the input.
Returns the absolute value of the input.
Returns the smallest integer that is greater than or equal to the input.
Returns the largest integer that is less than or equal to the input.
Rounds the input to the nearest integer. Halfway values are rounded away from zero. For example, round (float -1.5) evaluates to -2.
Returns the cosine of the input.
Returns the sine of the input.
Returns the tangent of the input.
Returns the arccosine of the input.
Returns the arcsine of the input.
Returns the arctangent of the input.
Returns the mathematical constant e.
Returns the natural logarithm of the input.
Returns mathematical constant ln(2).
Returns the base-ten logarithm of the input.
Returns the base-two logarithm of the input.
Gets the current zoom level. Note that in style layout and paint properties, zoom may only appear as the input to a top-level step or interpolate expression.
Gets the kernel density estimation of a pixel in a heatmap layer, which is a relative measure of how many data points are crowded around a particular pixel. Can only be used in the heatmapColor property.
Gets the progress along a gradient line. Can only be used in the lineGradient property.
These are required for various layer properties.
Encodes the relation to which something is measured or aligned to. The exact details are explained in the docs of each property supporting this. Some properties support the anchorAuto value, these have the type Anchor Auto, other don't and have the type Anchor Never.
Relativeto the map.
Relative to the viewport.
Automatic behaviour, that may vary based on circumstance between viewport and map.
Which part of the object is placed closest to the Anchor.
Scaling an icon to fit associated text.
The icon is displayed at its intrinsic aspect ratio.
The icon is scaled in the x-dimension to fit the width of the text.
The icon is scaled in the y-dimension to fit the height of the text.
The icon is scaled in both x- and y-dimensions.
Display of line endings.
A cap with a squared-off end which is drawn to the exact endpoint of the line.
A cap with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line.
A cap with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width.
Display of lines when joining.
A join with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line's width.
A join with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line's width and centered on the endpoint of the line.
A join with a sharp, angled corner which is drawn with the outer sides beyond the endpoint of the path until they meet.
Label placement relative to its geometry.
The label is placed at the point where the geometry is located.
The label is placed along the line of the geometry. Can only be used on LineString and Polygon geometries.
The label is placed at the center of the line of the geometry. Can only be used on LineString and Polygon geometries. Note that a single feature in a vector tile may contain multiple line geometries.
The text is aligned to the left.
The text is centered.
The text is aligned to the right.
Specifies how to capitalize text.
The text is not altered.
Forces all letters to be displayed in uppercase.
Forces all letters to be displayed in lowercase.
(Bi)linear filtering interpolates pixel values using the weighted average of the four closest original source pixels creating a smooth but blurry look when overscaled.
Nearest neighbor filtering interpolates pixel values using the nearest original source pixel creating a sharp but pixelated look when overscaled.
Expressions are zero overhead wrappers over the underlying JSON language that attempt to provide some type safety.
Note however, that while being a strictly typed language, it has slighlty different semantics tham Elm:
Float. You will notice that theintfunction takes an Elm int value and converts it to anExpression expr Float.null. There is noMaybetype. You can use thecoalescefunction to handle this.List,Array, and tuples. Hence all collections are labeled asArray.Object. The keys are alwaysString, but the values can be of mixed types. Hence retrieving values from them makes code untyped.assert...functions. This will generate a runtime error if the type doesn't match. This should be necessary only rarely.The
exprTypecan be:CameraExpressionDataExpressionThe intent is to help you not break your style by using a DataExpression (for example) where it isn't supported. However, this isn't entirely foolproof, so some caution is advised.