Skip to content

Evaluate an expression

A style expression evaluates the same way outside a map as on a layer, so a host can show a value that matches what the layer draws, or filter its own features with a layer’s filter. Expressions follow the same rules as in MapLibre GL JS’s createExpression().

Parse an expression once. The handle needs no runtime or map, and any thread can evaluate it, including several threads at once.

evaluate-expression.c
mln_style_expression radius = MLN_HANDLE_NULL;
mln_status status = mln_style_expression_create(
view("[\"interpolate\",[\"linear\"],[\"get\",\"mag\"],1,4,6,24]"), NULL,
&radius, NULL
);
if (status != MLN_STATUS_OK) return NULL;

The inputs hold what the expression reads: the zoom, a GeoJSON feature, its feature state, the global state, and the other values that a layer passes. An expression that needs an input you leave out, such as the zoom or the feature, fails to evaluate.

evaluate-expression.c
mln_style_expression_inputs inputs = mln_style_expression_inputs_default();
inputs.fields = MLN_STYLE_EXPRESSION_INPUT_FEATURE;
inputs.feature = view(feature);

The result is JSON. A call reports the result’s length whether or not the buffer held it, without the NUL terminator, so a C host can ask for the length first and then fill a buffer one byte longer. The language bindings size the buffer themselves and return the JSON.

evaluate-expression.c
size_t length = 0;
status =
mln_style_expression_evaluate(radius, &inputs, NULL, 0, &length, NULL);
char* json = status == MLN_STATUS_OK ? malloc(length + 1) : NULL;
if (json != NULL) {
status = mln_style_expression_evaluate(
radius, &inputs, json, length + 1, &length, NULL
);
}

The style expression reference defines the inputs, the expected result type, and how each value serializes.