CARTO VL

This is a DEPRECATED VERSION of CARTO VL. You can find more information about the support and the availability of the different CARTO VL versions.

CARTO VL is a JavaScript library to create custom Location Intelligence applications over vector rendering.

This library is still under support but it will not be further developed. We don’t recommend starting new projects with it as it will eventually become deprecated. Instead, learn more about our current CARTO for deck.gl library here

Interactivity ( layerList , options )

Interactivity purpose is to allow the reception and management of user-generated events, like clicking, over layer features.

To create a Interactivity object an array of carto.Layer is required. Events fired from interactivity objects will refer to the features of these layers and only these layers. Moreover, the order of the features in the events will be determined by the order of the layers in this list.

Parameters
Name Description
layerList carto.Layer | carto.Layer Array

carto.Layer or array of carto.Layer , events will be fired based on the features of these layers. The array cannot be empty, and all the layers must be attached to the same map.

options
Name Description
options.autoChangePointer boolean

A boolean flag indicating if the cursor should change when the mouse is over a feature.

Default: true

Example
1
2
3
4
5
const interactivity = new carto.Interactivity(layer);
interactivity.on('click', event => {
  style(event.features);
  show(event.coordinates);
});
CLICK TO COPY
No String example available

Layer ( id , source , viz )

A Layer is the primary way to visualize geospatial data.

To create a layer a source and viz are required:

  • The source is used to know what data will be displayed in the Layer.

  • The viz is used to know how to draw the data in the Layer, Viz instances can only be bound to one single layer.

Parameters
Name Description
id string

The ID of the layer. Can be used in the addTo function

source carto.source.Base

The source of the data

viz carto.Viz

The description of the visualization of the data

Example
1
const layer = new carto.Layer('layer0', source, viz);
CLICK TO COPY
No String example available

version

The version of CARTO VL in use as specified in package.json and the GitHub release.

off ( eventName , layerList , callback )

Remove an event handler for the given event name, layer list and callback.

Parameters
Name Description
eventName string

event

layerList carto.Layer

List of layers

callback function

Handler function to unregister

on ( eventName , layerList , callback )

Register an event handler for the given event name and for the given list of layers. Valid names are: loaded , updated .

The 'loaded' event will be fired when all the layers are loaded (and their 'loaded' events are fired).

The 'updated' event will be fired whenever one of the layers fired an 'updated' event, but throttled by requestAnimationFrame to return a maximum of one event per frame.

Parameters
Name Description
eventName string

Supported event names are 'loaded' and 'updated'

layerList carto.Layer Array

List of layers

callback

setDefaultAuth ( auth )

Set default authentication parameters: user and apiKey.

Parameters
Name Description
auth
Name Description
auth.user string

Name of the user

auth.apiKey string

API key used to authenticate against CARTO

setDefaultConfig ( config )

Set default configuration parameters

Parameters
Name Description
config
Name Description
config.serverURL string

='https://{user}.carto.com' - Template URL of the CARTO Maps API server

carto.expressions

Expressions are used to define visualizations, a visualization (viz) is a set named properties and variables and its corresponding values: expressions. A viz has the following properties:

  • color : fill color of points and polygons and color of lines

  • strokeColor : stroke/border color of points and polygons, not applicable to lines

  • width : fill diameter of points, thickness of lines, not applicable to polygons

  • strokeWidth : stroke width of points and polygons, not applicable to lines

  • filter : filter features by removing from rendering and interactivity all the features that don't pass the test

  • symbol - show an image instead in the place of points

  • symbolPlacement - when using symbol , offset to apply to the image

  • order : - rendering order of the features, only applicable to points. See carto.expressions.asc , carto.expressions.desc and carto.expressions.noOrder

  • resolution : - resolution of the property-aggregation functions, only applicable to points. Default resolution is 1. Custom values must be greater than 0 and lower than 256. A resolution of N means points are aggregated to grid cells NxN pixels. Unlinke Torque resolution , the aggregated points are placed in the centroid of the cluster, not in the center of the grid cell.

For example the point diameter could be using the add expression:

				const viz = new carto.Viz({
  width: carto.expressions.add(5, 5)  // Equivalent to `width: 10`
});
		

You can use dataset properties inside expressions. Imagine we are representing cities in a map, we can make the point width proportional to the population using the property / prop expression.

				const viz = new carto.Viz({
  width: carto.expressions.prop('population')
});
		

Multiple expressions can be combined to form more powerful ones, for example lets divide the population between a number using the div expression to make points smaller:

				const s = carto.expressions; // We use this alias along documentation.
const viz = new carto.Viz({
  width: s.div(
    s.prop('population'),
    10000
 )
});
		

All these expressions can be used also in a String API form. This API is a more compact way to create and use expressions. It has shortcut notation to access your feature properties using the $ symbol. It also allows inline comments using the JavaScript syntax.

				const viz = new carto.Viz(`
  width: $population / 10000  // Size proportional to the population for each feature
`);
		

Although the combination of expressions is very powerful, you must be aware of the different types to produce valid combinations. For example, the previous example is valid since we assumed that 'population' is a numeric property, it won't be valid if it was a categorical property. Each expression defines some restrictions regarding their parameters, particularly, the type of their parameters.

The most important types are:

  • Number expression. Expressions that contains numbers, both integers and floating point numbers. Boolean types are emulated by this type, being 0 false, and 1 true.

  • Category expression. Expressions that contains categories. Categories can have a limited set of values, like the country or the region of a feature.

  • Color expression. Expressions that contains colors. An alpha or transparency channel is included in this type.

Animation

Animation class

This class is instanced automatically by using the animation function. It is documented for its methods.

Extends

carto.source.Base

Base

Abstract expression class

All expressions listed in carto.expressions inherit from this class so any of them can be used where an Expression is required as long as the types match.

This means that you can't use a numeric expression where a color expression is expected.

carto.expressions.palettes

Color palettes.

Palettes are constants that allow to use CARTOColors and ColorBrewer palettes easily. Use them with a ramp

The following palettes are available in the namespace carto.expressions.palettes .

				BURG, BURGYL, REDOR, ORYEL, PEACH, PINKYL, MINT, BLUGRN, DARKMINT, EMRLD, AG_GRNYL, BLUYL, TEAL, TEALGRN,
PURP, PURPOR, SUNSET, MAGENTA, SUNSETDARK, AG_SUNSET, BRWNYL, ARMYROSE, FALL, GEYSER, TEMPS, TEALROSE, TROPIC,
EARTH, ANTIQUE, BOLD, PASTEL, PRISM, SAFE, VIVID, CB_YLGN, CB_YLGNBU, CB_GNBU, CB_BUGN, CB_PUBUGN, CB_PUBU,
CB_BUPU, CB_RDPU, CB_PURD, CB_ORRD, CB_YLORRD, CB_YLORBR, CB_PURPLES, CB_BLUES, CB_GREENS, CB_ORANGES, CB_REDS,
CB_GREYS, CB_PUOR, CB_BRBG, CB_PRGN, CB_PIYG, CB_RDBU, CB_RDGY, CB_RDYLBU, CB_SPECTRAL, CB_RDYLGN, CB_ACCENT,
CB_DARK2, CB_PAIRED, CB_PASTEL1, CB_PASTEL2, CB_SET1, CB_SET2, CB_SET3
		
Example Using a color scheme.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.prop('type'), s.palettes.PRISM);
});
CLICK TO COPY
Example Using a color scheme.
1
2
3
const viz = new carto.Viz(`
  color: ramp($type, PRISM)
`);
CLICK TO COPY

ViewportHistogram ( input , weight , size )

Generates an histogram.

The histogram can be based on a categorical expression, in which case each category will correspond to a histogram bar. The histogram can be based on a numeric expression, in which case the minimum and maximum will be computed automatically and bars will be generated at regular intervals between the minimum and maximum. The number of bars in this case is controllable through the size parameter.

Histograms are useful to get insights and create widgets outside the scope of CARTO VL, see the following example for more info.

Parameters
Name Description
input Number

expression to base the histogram

weight Number

Weight each occurrence differently based on this weight, defaults to 1 , which will generate a simple, non-weighted count.

size Number

Optional (defaults to 1000). Number of bars to use if x is a numeric expression

Returns

Histogram

Histogram
Example Create and use an histogram.
1
2
3
4
5
6
7
8
9
10
11
12
13
const s = carto.expressions;
const viz = new carto.Viz(`
         @categoryHistogram: viewportHistogram($type)
         @numericHistogram:  viewportHistogram($amount, 1, 3)
`);
...
console.log(viz.variables.categoryHistogram.eval());
// [{x: 'typeA', y: 10}, {x: 'typeB', y: 20}]
// There are 10 features of type A and 20 of type B

console.log(viz.variables.numericHistogram.eval());
// [{x: [0,10],  y: 20}, {x: [10,20],  y: 7}, {x: [20, 30], y: 3}]
// There are 20 features with an amount between 0 and 10, 7 features with an amount between 10 and 20, and 3 features with an amount between 20 and 30
CLICK TO COPY

abs ( x )

Compute the absolute value of a number x.

Parameters
Name Description
x Number

Numeric expression to compute the absolute value

Returns
Number
Example Abs.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.abs(-100)  // 100
});
CLICK TO COPY
Example Abs.
1
2
3
const viz = new carto.Viz(`
  width: abs(-100) // 100
`);
CLICK TO COPY

add ( x , y )

Add two numeric expressions.

Parameters
Name Description
x Number | Color

First value to add

y Number | Color

Second value to add

Returns

Result of the addition

Number | Color
Example Number addition.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.add(10, 2)  // 12
});
CLICK TO COPY
Example Number addition.
1
2
3
const viz = new carto.Viz(`
  width: 10 + 2  // Equivalent to add(10, 2)
`);
CLICK TO COPY

alphaNormalize ( input , normalizer )

Override the opacity (alpha channel) of a color to normalize the input color by a normalizer property.

This is implemented as `opacity(input, normalizer/globalMax(normalizer))

Parameters
Name Description
input Color

input color to normalize

normalizer Number

numeric property that will be used to normalize the input color

Returns
Color
Example Normalize an input property ($winner_party) by a second property ($voters).
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.alphaNormalize(
             s.ramp(s.prop('winner_party'), [red, blue]),
             s.prop('voters')
         )
});
CLICK TO COPY
Example Normalize an input property ($winner_party) by a second property ($voters).
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
  color: alphaNormalize(
             ramp($winner_party, [red, blue]),
             $voters
         )
});
CLICK TO COPY

and ( x , y )

Perform a binary AND between two numeric expressions. If the numbers are different from 0 or 1 this performs a fuzzy and operation . This fuzzy behavior will allow transitions to work in a continuos, non-discrete, fashion.

This returns a number expression where 0 means false and 1 means true .

Parameters
Name Description
x Number

First value of the expression

y Number

Second value of the expression

Returns

Result of the expression

Number
Example Show only elements with price < 30 AND category === 'fruit'.
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.and(
    s.lt(s.prop('price'), 30),
    s.eq(s.prop('category'), 'fruit')
  )
});
CLICK TO COPY
Example Show only elements with price < 30 AND category === 'fruit'.
1
2
3
const viz = new carto.Viz(`
  filter: $price < 30 and $category === 'fruit'  // Equivalent to and(lt($price, 30), eq($category, 'fruit'))
`);
CLICK TO COPY

animation ( input , duration , fade )

Create an animated temporal filter (animation).

Parameters
Name Description
input Number

input to base the temporal filter, if input is a property, the beginning and end of the animation will be determined by the minimum and maximum timestamps of the property on the dataset, this can be problematic if outliers are present. Otherwise input must be a number expression in which 0 means beginning of the animation and 1 means end. If input is NULL or NaN the filter won't be passed at any moment of the animation.

It can be combined with linear and time expressions.

duration Number

duration of the animation in seconds, optional, defaults to 10 seconds

fade Fade

fadeIn/fadeOut configuration, optional, defaults to 0.15 seconds of fadeIn and 0.15 seconds of fadeOut

Returns
Number
Example Temporal map by $day (of numeric type), with a duration of 40 seconds, fadeIn of 0.1 seconds and fadeOut of 0.3 seconds.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  width: 2,
  color: s.ramp(s.linear(s.clusterAvg(s.prop('temp'), 0, 30)), s.palettes.TEALROSE),
  filter: s.animation(s.prop('day'), 40, s.fade(0.1, 0.3))
});
CLICK TO COPY
Example Temporal map by $day (of numeric type), with a duration of 40 seconds, fadeIn of 0.1 seconds and fadeOut of 0.3 seconds.
1
2
3
4
5
const viz = new carto.Viz(`
  width: 2
  color: ramp(linear(clusterAvg($temp), 0,30), tealrose)
  filter: animation($day, 40, fade(0.1, 0.3))
`);
CLICK TO COPY
Example Temporal map by $date (of date type), with a duration of 40 seconds, fadeIn of 0.1 seconds and fadeOut of 0.3 seconds.
1
2
3
4
5
const viz = new carto.Viz({
  width: 2,
  color: s.ramp(s.linear(s.clusterAvg(s.prop('temp'), 0, 30)), s.palettes.TEALROSE),
  filter: s.animation(s.linear(s.prop('date'), s.time('2022-03-09T00:00:00Z'), s.time('2033-08-12T00:00:00Z')), 40, s.fade(0.1, 0.3))
});
CLICK TO COPY
Example Temporal map by $date (of date type), with a duration of 40 seconds, fadeIn of 0.1 seconds and fadeOut of 0.3 seconds.
1
2
3
4
5
const viz = new carto.Viz(`
  width: 2
  color: ramp(linear(clusterAvg($temp), 0,30), tealrose)
  filter: animation(linear($date, time('2022-03-09T00:00:00Z'), time('2033-08-12T00:00:00Z')), 40, fade(0.1, 0.3))
`);
CLICK TO COPY

array ( elements )

Wrapper around arrays. Explicit usage is unnecessary since CARTO VL will wrap implicitly all arrays using this function.

Parameters
Name Description
elements Number Array | Category Array | Color Array | Date Array | Image Array
Returns
Array

asc ( by )

Order ascending by a provided expression. NOTE: only works with width() .

Note: ordering expressions won't assure a perfect ordering. Features will be distributed in different buckets with the original order, and those buckets will be ordered. This guarantees a maximum error, but not a perfect order. For most operations this is imperceptible, but usage of order in combination with animation or multi-scale expressions ( zoomrange and scaled ) may result in artifacts.

Parameters
Name Description
by carto.expressions.Width

must be width()

Returns
Order
Example Ascending order based on width.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  order: s.asc(s.width())
});
CLICK TO COPY
Example Ascending order based on width.
1
2
3
const viz = new carto.Viz(`
  order: asc(width())
`);
CLICK TO COPY

between ( value , lowerLimit , upperLimit )

Check if a given value is contained within an inclusive range (including the limits).

This returns a numeric expression where 0 means false and 1 means true .

Parameters
Name Description
value Number

Numeric expression that is going to be tested against the [lowerLimit, upperLimit] range

lowerLimit Number

Numeric expression with the lower limit of the range

upperLimit Number

Numeric expression with the upper limit of the range

Returns

Numeric expression with the result of the check

Number
Example Display only cities where the population density is within the [50,100] range.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.between(s.prop('dn'), 50, 100);
});
CLICK TO COPY
Example Display only cities where the population density is within the [50,100] range.
1
2
3
const viz = new carto.Viz(`
  filter: between($dn, 50, 100)
`);
CLICK TO COPY

blend ( a , b , mix )

Linearly interpolate from a to b based on mix .

Parameters
Name Description
a Number | Color

Numeric or color expression, a type must match b type

b Number | Color

Numeric or color expression, b type must match a type

mix Number

Numeric expression with the interpolation parameter in the [0,1] range

Returns

Numeric or color expression with the same type as a and b

Number | Color
Example Blend based on the zoom level to display a bubble map at high zoom levels and display fixed-sized points at low zoom levels.
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.blend(3,
                 s.prop('dn'),
                 s.linear(s.zoom(), 10, 14))
          );
});
CLICK TO COPY
Example Blend based on the zoom level to display a bubble map at high zoom levels and display fixed-sized points at low zoom levels.
1
2
3
4
5
6
const viz = new carto.Viz(`
  width: blend(3,
               $dn,
               linear(zoom(), 10, 14)
         )
`);
CLICK TO COPY

buckets ( property , breakpoints )

Given a property create "sub-groups" based on the given breakpoints.

This returns a number or category expression depending on the input values.

Parameters
Name Description
property Number | Category

The property to be evaluated and interpolated

breakpoints Number Array | Category Array

Expression containing the different breakpoints.

Returns
Number | Category
Example Display a traffic dataset in 4 colors depending on the numeric speed.
1
2
3
4
5
6
7
8
9
10
11
12
13
// Using the buckets `expression` we divide the dataset into 4 buckets according to the speed
// - From -inf to 29
// - From 30 to 79
// - From 80 to 119
// - From 120 to +inf
// Values lower than 0 will be in the first bucket and values higher than 120 will be in the last one.
const s = carto.expressions;
const viz = new carto.Viz({
   color: s.ramp(
     s.buckets(s.prop('speed'), [30, 80, 120]),
     s.palettes.PRISM
   )
});
CLICK TO COPY
Example Display a traffic dataset in 4 colors depending on the numeric speed.
1
2
3
4
5
6
7
8
9
// Using the buckets `expression` we divide the dataset into 4 buckets according to the speed
// - From -inf to 29
// - From 30 to 79
// - From 80 to 119
// - From 120 to +inf
// Values lower than 0 will be in the first bucket and values higher than 120 will be in the last one.
const viz = new carto.Viz(`
   color: ramp(buckets($speed, [30, 80, 120]), PRISM)
`);
CLICK TO COPY
Example Display a traffic dataset is 3 colors depending on the category procesedSpeed.
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(
    s.buckets(s.prop('procesedSpeed'), ['slow', 'medium', 'high']),
    s.palettes.PRISM)
  )
});
CLICK TO COPY
Example Display a traffic dataset is 3 colors depending on the category procesedSpeed.
1
2
3
const viz = new carto.Viz(`
   color: ramp(buckets($procesedSpeed, ['slow', 'medium', 'high']), PRISM)
`);
CLICK TO COPY

ceil ( x )

Compute the ceil of the given expression. Find the nearest integer that is greater than or equal to the expression value.

  • When x is equal to 0.8 ceil(x) will be evaluated to 1

  • When x is equal to 1.3 ceil(x) will be evaluated to 2

Parameters
Name Description
x Number

Number to compute the ceil value

Returns
Number
Example Ceil.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.ceil(5.1);  // 6
});
CLICK TO COPY
Example Ceil.
1
2
3
const viz = new carto.Viz(`
  width: ceil(5.1)
`);
CLICK TO COPY

cielab ( l , a , b )

Evaluates to a CIELab color.

Parameters
Name Description
l Number

The lightness of the color

a Number

The green–red color component

b Number

The blue–yellow color component

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.cielab(32.3, 79.2, -107.86)
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: cielab(32.3, 79.2, -107.86)
`);
CLICK TO COPY

clusterAvg ( property )

Aggregate using the average. This operation disables the access to the property except within other cluster aggregate functions.

Note: clusterAvg can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number

Column of the table to be aggregated

Returns

Aggregated column

Number
Example Use cluster average of the population as width.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.clusterAvg(s.prop('population'))
});
CLICK TO COPY
Example Use cluster average of the population as width.
1
2
3
const viz = new carto.Viz(`
  width: clusterAvg($population)
`);
CLICK TO COPY

clusterCount

Count of features per cluster.

Note: clusterCount has no input parameters and if data is not aggregated, it always returns 1

Returns

Cluster feature count

Number
Example Use cluster count for width.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.clusterCount() / 50
});
CLICK TO COPY
Example Use cluster count for width.
1
2
3
const viz = new carto.Viz(`
  width: clusterCount() / 50
`);
CLICK TO COPY

clusterMax ( property )

Aggregate using the maximum. This operation disables the access to the property except within other cluster aggregate functions.

Note: clusterMax can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number

Column of the table to be aggregated

Returns

Aggregated column

Number
Example Use cluster maximum of the population as width.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.clusterMax(s.prop('population'))
});
CLICK TO COPY
Example Use cluster maximum of the population as width.
1
2
3
const viz = new carto.Viz(`
  width: clusterMax($population)
`);
CLICK TO COPY

clusterMin ( property )

Aggregate using the minimum. This operation disables the access to the property except within other cluster aggregate functions.

Note: clusterMin can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number

Column of the table to be aggregated

Returns

Aggregated column

Number
Example Use cluster minimum of the population as width.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.clusterMin(s.prop('population'))
});
CLICK TO COPY
Example Use cluster minimum of the population as width.
1
2
3
const viz = new carto.Viz(`
  width: clusterMin($population)
`);
CLICK TO COPY

clusterMode ( property )

Aggregate using the mode. This operation disables the access to the property except within other cluster aggregate functions.

Note: clusterMode can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Category

Column of the table to be aggregated

Returns

Aggregated column

Category
Example Use cluster mode of the population in a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.clusterMode(s.prop('category')), s.palettes.PRISM)
});
CLICK TO COPY
Example Use cluster mode of the population in a color ramp.
1
2
3
const viz = new carto.Viz(`
  color: ramp(clusterMode($category), PRISM)
`);
CLICK TO COPY

clusterSum ( property )

Aggregate using the sum. This operation disables the access to the property except within other cluster aggregate functions.

Note: clusterSum can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number

Column of the table to be aggregated

Returns

Aggregated column

Number
Example Use cluster sum of the population as width.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.clusterSum(s.prop('population'))
});
CLICK TO COPY
Example Use cluster sum of the population as width.
1
2
3
const viz = new carto.Viz(`
  width: clusterSum($population)
`);
CLICK TO COPY

constant ( x )

Wraps a constant number. Implies a GPU optimization vs number expression .

Parameters
Name Description
x number

A number to be warped in a constant numeric expression

Returns

Numeric expression

Number
Example Creating a constant number expression.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.constant(15)
});
CLICK TO COPY
Example Creating a constant number expression.
1
2
3
const viz = new carto.Viz(`
  width: constant(15)
`);
CLICK TO COPY

cos ( x )

Compute the cosine of a number x.

Parameters
Name Description
x Number

Numeric expression to compute the cosine in radians

Returns
Number
Example Cos.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.cos(0)  // 1
});
CLICK TO COPY
Example Cos.
1
2
3
const viz = new carto.Viz(`
  width: cos(0)
`);
CLICK TO COPY

desc ( by )

Order descending by a provided expression. NOTE: only works with width() .

Note: ordering expressions won't assure a perfect ordering. Features will be distributed in different buckets with the original order, and those buckets will be ordered. This guarantees a maximum error, but not a perfect order. For most operations this is imperceptible, but usage of order in combination with animation or multi-scale expressions ( zoomrange and scaled ) may result in artifacts.

Parameters
Name Description
by carto.expressions.Width

must be width()

Returns
Order
Example Descending order based on width.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  order: s.desc(s.width())
});
CLICK TO COPY
Example Descending order based on width.
1
2
3
const viz = new carto.Viz(`
  order: desc(width())
`);
CLICK TO COPY

div ( numerator , denominator )

Divide two numeric expressions.

Parameters
Name Description
numerator Number | Color

Numerator of the division

denominator Number | Color

Denominator of the division

Returns

Result of the division

Number | Color
Example Number division.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.div(10, 2)  // 5
});
CLICK TO COPY
Example Number division.
1
2
3
const viz = new carto.Viz(`
  width: 10 / 2  // Equivalent to div(10, 2)
`);
CLICK TO COPY

eq ( x , y )

Compare if x is equal to a y.

This returns a numeric expression where 0 means false and 1 means true .

Parameters
Name Description
x Number | Category

Firt value of the comparison

y Number | Category

Second value of the comparison

Returns

Result of the comparison: 0 or 1

Number
Example Compare two numbers to show only elements with price equal to 30.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.eq(s.prop('price'), 30)
});
CLICK TO COPY
Example Compare two numbers to show only elements with price equal to 30.
1
2
3
const viz = new carto.Viz(`
  filter: $price == 30  // Equivalent to eq($price, 30)
`);
CLICK TO COPY

fade ( param1 , param2 )

Create a FadeIn/FadeOut configuration. See animation for more details.

Parameters
Name Description
param1 Number

Expression of type number or Number

param2 Number

Expression of type number or Number

Returns
Fade
Example Fade in of 0.1 seconds, fade out of 0.3 seconds.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.animation(s.prop('day'), 40, s.fade(0.1, 0.3))
});
CLICK TO COPY
Example Fade in of 0.1 seconds, fade out of 0.3 seconds.
1
2
3
const viz = new carto.Viz(`
  filter: animation($day, 40, fade(0.1, 0.3))
`);
CLICK TO COPY
Example Fade in and fade out of 0.5 seconds.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.animation(s.prop('day'), 40, s.fade(0.5))
});
CLICK TO COPY
Example Fade in and fade out of 0.5 seconds.
1
2
3
const viz = new carto.Viz(`
  filter: animation($day, 40, fade(0.5))
`);
CLICK TO COPY
Example Fade in of 0.3 seconds without fading out.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.animation(s.prop('day'), 40, s.fade(0.1, s.HOLD))
});
CLICK TO COPY
Example Fade in of 0.3 seconds without fading out.
1
2
3
const viz = new carto.Viz(`
  filter: animation($day, 40, fade(0.3, HOLD))
`);
CLICK TO COPY

floor ( x )

Compute the floor of the given expression. Find the nearest integer less than or equal to the expression value.

  • When x is equal to 0.8 floor(x) will be evaluated to 0

  • When x is equal to 1.3 floor(x) will be evaluated to 1

Parameters
Name Description
x Number

Number to compute the floor value

Returns
Number
Example Floor.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.floor(5.9)  // 5
});
CLICK TO COPY
Example Floor.
1
2
3
const viz = new carto.Viz(`
  width: floor(5.9)
`);
CLICK TO COPY

globalAvg ( property )

Return the average of the feature property for the entire source data.

Note: globalAvg can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number

property expression of number type

Returns

Result of the aggregation

Number
Example Assign the global average of the `amount` property to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     g_avg: s.globalAvg(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the global average of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
  @g_avg: globalAvg($amount)
`);
CLICK TO COPY

globalCount ( property )

Return the feature count for the entire source data.

Note: globalCount can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number

property expression

Returns

Result of the aggregation

Number
Example Assign the global count of the `amount` property to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     g_count: s.globalCount(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the global count of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
  @g_count: globalCount($amount)
`);
CLICK TO COPY

globalEqIntervals ( input , n )

Classify input by using the equal intervals method with n buckets.

It will classify the input based on the entire dataset without filtering by viewport or by filter .

Parameters
Name Description
input Number

The input expression to classify

n number

Number of buckets

Returns
Category
Example Use global equal intervals to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.globalEqIntervals(s.prop('density'), 5), s.palettes.PRISM)
});
CLICK TO COPY
Example Use global equal intervals to define a color ramp.
1
2
3
const viz = new carto.Viz(`
  color: ramp(globalEqIntervals($density, 5), PRISM)
`);
CLICK TO COPY

globalMax ( property )

Return the maximum of the feature property for the entire source data.

Note: globalMax can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number | Date

property expression of date or number type

Returns

Result of the aggregation

Number | Date
Example Assign the global maximum of the `amount` property to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     g_max: s.globalMax(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the global maximum of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
  @g_max: globalMax($amount)
`);
CLICK TO COPY

globalMin ( property )

Return the minimum of the feature property for the entire source data.

Note: globalMin can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number | Date

property expression of date or number type

Returns

Result of the aggregation

Number | Date
Example Assign the global minimum of the `amount` property to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     g_min: s.globalMin(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the global minimum of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
  @g_min: globalMin($amount)
`);
CLICK TO COPY

globalPercentile ( property , percentile )

Return the Nth percentile of an numeric property for the entire source data.

Parameters
Name Description
property Number

numeric property

percentile Number

Numeric expression in the [0, 100] range

Returns

Result of the aggregation

Number
Example Assign the 90th percentile of the `amount` property for the entire dataset to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     v_percentile: s.globalPercentile(s.prop('amount'), 90)
  }
});
CLICK TO COPY
Example Assign the 90th percentile of the `amount` property for the entire dataset to a variable.
1
2
3
const viz = new carto.Viz(`
  @v_percentile: globalPercentile($amount, 90)
`);
CLICK TO COPY

globalQuantiles ( input , n )

Classify input by using the quantiles method with n buckets.

It will classify the input based on the entire dataset without filtering by viewport or by filter .

Parameters
Name Description
input Number

The input expression used in the quantiles

n number

Number of buckets to be returned

Returns
Category
Example Use global quantiles to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.globalQuantiles(s.prop('density'), 5), s.palettes.PRISM)
});
CLICK TO COPY
Example Use global quantiles to define a color ramp.
1
2
3
const viz = new carto.Viz(`
  color: ramp(globalQuantiles($density, 5), PRISM)
`);
CLICK TO COPY

globalSum ( property )

Return the sum of the feature property for the entire source data.

Note: globalSum can only be created by carto.expressions.prop , not other expressions.

Parameters
Name Description
property Number

property expression of number type

Returns

Result of the aggregation

Number
Example Assign the global sum of the `amount` property to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     g_sum: s.globalSum(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the global sum of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
  @g_sum: globalSum($amount)
`);
CLICK TO COPY

gt ( x , y )

Compare if x is greater than y.

This returns a numeric expression where 0 means false and 1 means true .

Parameters
Name Description
x Number

Firt value of the comparison

y Number

Firt value of the comparison

Returns

Result of the comparison: 0 or 1

Number
Example Compare two numbers to show only elements with price greater than 30.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.gt(s.prop('price'), 30)
});
CLICK TO COPY
Example Compare two numbers to show only elements with price greater than 30.
1
2
3
const viz = new carto.Viz(`
  filter: $price > 30  // Equivalent to gt($price, 30)
`);
CLICK TO COPY

gte ( x , y )

Compare if x is greater than or equal to y.

This returns a numeric expression where 0 means false and 1 means true .

Parameters
Name Description
x Number

Firt value of the comparison

y Number

Second value of the comparison

Returns

Result of the comparison: 0 or 1

Number
Example Compare two numbers to show only elements with price greater than or equal to 30.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.gte(s.prop('price'), 30)
});
CLICK TO COPY
Example Compare two numbers to show only elements with price greater than or equal to 30.
1
2
3
const viz = new carto.Viz(`
  filter: $price >= 30  // Equivalent to gte($price, 30)
`);
CLICK TO COPY

hex ( hexadecimalColor )

Create a color from its hexadecimal description.

Parameters
Name Description
hexadecimalColor string

Color in the #RGB, #RGBA, #RRGGBB or #RRGGBBAA format

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.hex('#00F');  // Equivalent to `color: '#00F'`
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: #00F  // Equivalent to hex('#00F')
`);
CLICK TO COPY

hsl ( h , s , l )

Evaluates to a hsl color.

Parameters
Name Description
h Number

hue of the color in the [0, 1] range

s Number

saturation of the color in the [0, 1] range

l Number

lightness of the color in the [0, 1] range

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.hsl(0.67, 1.0, 0.5)
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: hsl(0.67, 1.0, 0.5)
`);
CLICK TO COPY

hsla ( h , s , l , a )

Evaluates to a hsla color.

Parameters
Name Description
h Number

hue of the color in the [0, 1] range

s Number

saturation of the color in the [0, 1] range

l Number

lightness of the color in the [0, 1] range

a Number

alpha value of the color in the [0, 1] range

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.hsla(0.67, 1.0, 0.5, 1.0)
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: hsla(0.67, 1.0, 0.5, 1.0)
`);
CLICK TO COPY

hsv ( h , s , v )

Evaluates to a hsv color.

Parameters
Name Description
h Number

hue of the color in the [0, 1] range

s Number

saturation of the color in the [0, 1] range

v Number

value (brightness) of the color in the [0, 1] range

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.hsv(0.67, 1.0, 1.0)
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: hsv(0.67, 1.0, 1.0)
`);
CLICK TO COPY

hsva ( h , s , v , a )

Evaluates to a hsva color.

Parameters
Name Description
h Number

hue of the color in the [0, 1] range

s Number

saturation of the color in the [0, 1] range

v Number

value (brightness) of the color in the [0, 1] range

a Number

alpha value of the color in the [0, 1] range

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.hsva(0.67, 1.0, 1.0, 1.0)
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: hsva(0.67, 1.0, 1.0, 1.0)
`);
CLICK TO COPY

image ( url )

Image. Load an image and use it as a symbol.

Note: image RGB color will be overridden if the viz color property is set.

Parameters
Name Description
url string

Image path

Example Load a svg image.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  symbol: s.image('./marker.svg')
});
CLICK TO COPY
Example Load a svg image.
1
2
3
const viz = new carto.Viz(`
   symbol: image('./marker.svg')
`);
CLICK TO COPY

in ( value , list )

Check if a categorical value belongs to a list of categories.

Parameters
Name Description
value Category

Categorical expression to be tested against the whitelist

list Category Array

Multiple expression parameters that will form the whitelist

Returns

Numeric expression with the result of the check

Number
Example Display only cities where $type is 'metropolis' or 'capital'.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.in(s.prop('type'), ['metropolis', 'capital'])
});
CLICK TO COPY
Example Display only cities where $type is 'metropolis' or 'capital'.
1
2
3
const viz = new carto.Viz(`
  filter: $type in ['metropolis', 'capital']
`);
CLICK TO COPY

isNaN ( x )

Check if a numeric expression is NaN.

This returns a numeric expression where 0 means false and 1 means true .

Parameters
Name Description
x Number

Numeric expression to check

Returns
Number
Example Filter NaN values of the `numeric` property.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.not(s.isNaN(s.prop('numeric')))
});
CLICK TO COPY
Example Filter NaN values of the `numeric` property.
1
2
3
const viz = new carto.Viz(`
  filter: not(isNaN($numeric))
`);
CLICK TO COPY

linear ( input , min , max )

Linearly interpolates the value of a given input between a minimum and a maximum. If min and max are not defined they will default to globalMin(input) and globalMax(input) .

Parameters
Name Description
input Number | Date

The input to be evaluated and interpolated, can be a numeric property or a date property

min Number | Date

Numeric or date expression pointing to the lower limit

max Number | Date

Numeric or date expression pointing to the higher limit

Returns
Number | Date
Example Color by $speed using the CARTOColor Prism by assigning the first color in Prism to features with speeds of 10 or less, the last color in Prism to features with speeds of 100 or more and a interpolated value for the speeds in between.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.linear(s.prop('speed'), 10, 100), s.palettes.PRISM)
});
CLICK TO COPY
Example Color by $speed using the CARTOColor Prism by assigning the first color in Prism to features with speeds of 10 or less, the last color in Prism to features with speeds of 100 or more and a interpolated value for the speeds in between.
1
2
3
const viz = new carto.Viz(`
  color: ramp(linear($speed, 10, 100), PRISM)
`);
CLICK TO COPY

log ( x )

Compute the natural logarithm (base e) of a number x.

Parameters
Name Description
x Number

Numeric expression to compute the natural logarithm

Returns
Number
Example Natural Logarithm.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.log(10)  // 2.302585092994046
});
CLICK TO COPY
Example Natural Logarithm.
1
2
3
const viz = new carto.Viz(`
  width: log(10)
`);
CLICK TO COPY

lt ( x , y )

Compare if x is lower than y.

This returns a numeric expression where 0 means false and 1 means true .

Parameters
Name Description
x Number

Firt value of the comparison

y Number

Second value of the comparison

Returns

Result of the comparison: 0 or 1

Number
Example Compare two numbers to show only elements with price less than 30.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.lt(s.prop('price'), 30)
});
CLICK TO COPY
Example Compare two numbers to show only elements with price less than 30.
1
2
3
const viz = new carto.Viz(`
  filter: $price < 30  // Equivalent to lt($price, 30)
`);
CLICK TO COPY

lte ( x , y )

Compare if x is lower than or equal to y.

This returns a numeric expression where 0 means false and 1 means true .

Parameters
Name Description
x Number

Firt value of the comparison

y Number

Second value of the comparison

Returns

Result of the comparison: 0 or 1

Number
Example Compare two numbers to show only elements with price less than or equal to 30.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.lte(s.prop('price'), 30)
});
CLICK TO COPY
Example Compare two numbers to show only elements with price less than or equal to 30.
1
2
3
const viz = new carto.Viz(`
  filter: $price <= 30  // Equivalent to lte($price, 30)
`);
CLICK TO COPY

mod ( x , y )

Modulus of two numeric expressions, mod returns a numeric expression with the value of x modulo y. This is computed as x - y * floor(x/y).

Parameters
Name Description
x Number

First value of the modulus

y Number

Second value of the modulus

Returns

Result of the modulus

Number
Example Number modulus.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.mod(10, 6)  // 4
});
CLICK TO COPY
Example Number modulus.
1
2
3
const viz = new carto.Viz(`
  width: 10 % 6  // Equivalent to mod(10, 6)
`);
CLICK TO COPY

mul ( x , y )

Multiply two numeric expressions.

Parameters
Name Description
x Number | Color

First value to multiply

y Number | Color

Second value to multiply

Returns

Result of the multiplication

Number | Color
Example Number multiplication.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.mul(5, 5)  // 25
});
CLICK TO COPY
Example Number multiplication.
1
2
3
const viz = new carto.Viz(`
  width: 5 * 5  // Equivalent to mul(5, 5)
`);
CLICK TO COPY

namedColor ( name )

Create a color from its name.

Parameters
Name Description
name string

The name of the color

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.namedColor('blue')  // Equivalent to `color: 'blue'`
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: blue  // Equivalent to namedColor('blue')
`);
CLICK TO COPY

neq ( x , y )

Compare if x is different than y.

This returns a number expression where 0 means false and 1 means true .

Parameters
Name Description
x Number | Category

Firt value of the comparison

y Number | Category

Second value of the comparison

Returns

Result of the comparison: 0 or 1

Number
Example Compare two numbers to show only elements with price not equal to 30.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.neq(s.prop('price'), 30);
});
CLICK TO COPY
Example Compare two numbers to show only elements with price not equal to 30.
1
2
3
const viz = new carto.Viz(`
  filter: $price != 30  // Equivalent to neq($price, 30)
`);
CLICK TO COPY

nin ( value , list )

Check if value does not belong to the list of elements.

Parameters
Name Description
value Category

Categorical expression to be tested against the blacklist

list Category Array

Multiple expression parameters that will form the blacklist

Returns

Numeric expression with the result of the check

Number
Example Display only cities where $type is not 'metropolis' or 'capital'.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.nin(s.prop('type'), ['metropolis', 'capital'])
});
CLICK TO COPY
Example Display only cities where $type is not 'metropolis' or 'capital'.
1
2
3
const viz = new carto.Viz(`
  filter: $type nin ['metropolis', 'capital']
`);
CLICK TO COPY

noOrder

No order expression.

Returns
Order
Example No order.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  order: s.noOrder()
});
CLICK TO COPY
Example No order.
1
2
3
const viz = new carto.Viz(`
  order: noOrder()
`);
CLICK TO COPY

not ( x )

Compute the logical negation of the given expression. This is internally computed as 1 - x preserving boolean behavior and allowing fuzzy logic.

  • When x is equal to 1 not(x) will be evaluated to 0

  • When x is equal to 0 not(x) will be evaluated to 1

Parameters
Name Description
x Number

Number to compute the not value

Returns
Number
Example Not.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.not(0)  // 1
});
CLICK TO COPY
Example Not.
1
2
3
const viz = new carto.Viz(`
  width: not(0)
`);
CLICK TO COPY

now

Get the current timestamp. This is an advanced form of animation, animation expression is preferred.

Returns
Number
Example Update width during the time.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.mod(s.now(), 10)
});
CLICK TO COPY
Example Update width during the time.
1
2
3
const viz = new carto.Viz(`
  width: now() % 10
`);
CLICK TO COPY

opacity ( color , alpha )

Override the input color opacity.

Parameters
Name Description
color Color

Color expression to apply the opacity

alpha Number

Number expression with the alpha (transparency) value

Returns
Color
Example Display blue points with 50% opacity.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.opacity(s.rgb(0,0,255), 0.5)  // Equivalent to `s.rgba(0,0,255,0.5)`
});
CLICK TO COPY
Example Display blue points with 50% opacity.
1
2
3
const viz = new carto.Viz(`
  color: opacity(rgb(0,0,255), 0.5) // Equivalent to `rgba(0,0,255,0.5)`
`);
CLICK TO COPY

or ( x , y )

Perform a binary OR between two numeric expressions. If the numbers are different from 0 or 1 this performs a fuzzy or operation . This fuzzy behavior will allow transitions to work in a continuos, non-discrete, fashion.

This returns a number expression where 0 means false and 1 means true .

Parameters
Name Description
x Number

First value of the expression

y Number

Second value of the expression

Returns

Result of the expression

Number
Example Show only elements with price < 30 OR price > 1000.
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.or(
    s.lt(s.prop('price'), 30),
    s.gt(s.prop('price'), 1000)
  )
});
CLICK TO COPY
Example Show only elements with price < 30 OR price > 1000.
1
2
3
const viz = new carto.Viz(`
  filter: $price < 30 or $price > 1000  // Equivalent to or(lt($price, 30), gt($price, 1000))
`);
CLICK TO COPY

placement ( x , y )

Placement. Define an image offset relative to its size. Where:

  • symbolPlacement: placement(1,1) means to align the bottom left corner of the image with the point center.

  • symbolPlacement: placement(0,0) means to align the center of the image with the point center.

  • symbolPlacement: placement(-1,-1) means to align the top right corner of the image with the point center.

				          |1
          |
          |
-1 -------+------- 1
          |
          |
        -1|
		

You can also use align_center and align_bottom to set the simbol placement as follows:

  • symbolPlacement: align_bottom is equivalent to symbolPlacement: placement(0, 1)

  • symbolPlacement: align_center is equivalent to symbolPlacement: placement(0, 0)

Parameters
Name Description
x number

first numeric expression that indicates the image offset in the X direction.

y number

second numeric expression that indicates the image offset in the Y direction.

Returns

Numeric expression

Placement
Example Setting the aligment to the top corner of the image.
1
2
3
4
5
const s = carto.expressions;
const viz = new carto.Viz({
  symbol: s.image('./marker.svg').
  symbolPlacement: s.placement(1, 0)
});
CLICK TO COPY
Example Setting the aligment to the top corner of the image.
1
2
3
4
const viz = new carto.Viz(`
  symbol: image('./marker.svg')
  symbolPlacement: placement(1, 0)
`);
CLICK TO COPY

pow ( base , exponent )

Compute the base to the exponent power, return a numeric expression with the value of the first parameter raised to the power of the second. The result is undefined if x<0 or if x=0 and y≤0.

Parameters
Name Description
base Number

Base of the power

exponent Number

Exponent of the power

Returns

Result of the power

Number
Example Number power.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.pow(2, 3)  // 8
});
CLICK TO COPY
Example Number power.
1
2
3
const viz = new carto.Viz(`
  width: 2 ^ 3  // Equivalent to pow(2, 3)
`);
CLICK TO COPY

prop ( name )

Evaluates the value of a column for every row in the dataset.

For example think about a dataset containing 3 cities: Barcelona, Paris and London. The prop('name') will return the name of the current city for every point in the dataset.

Parameters
Name Description
name string

The property in the dataset that is going to be evaluated

Returns
Number | Category | Date
Example Display only cities with name different from "London".
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
 filter: s.neq(s.prop('name'), 'london')
});
CLICK TO COPY
Example Display only cities with name different from "London".
1
2
3
4
5
6
7
const viz = new carto.Viz(`
  filter: neq(prop('name'), 'london')
`);

const viz = new carto.Viz(`
  filter: $name != 'london'
`);
CLICK TO COPY

ramp ( input , palette )

Create a ramp: a mapping between an input (a numeric or categorical expression) and an output (a color palette or a numeric palette, to create bubble maps)

Categories to colors Categorical expressions can be used as the input for ramp in combination with color palettes. If the number of categories exceeds the number of available colors in the palette new colors will be generated by using CieLAB interpolation.

Categories to numeric Categorical expression can be used as the input for ramp in combination with numeric palettes. If the number of input categories doesn't match the number of numbers in the numeric palette, linear interpolation will be used.

Numeric expressions to colors Numeric expressions can be used as the input for ramp in combination with color palettes. Colors will be generated by using CieLAB interpolation.

Numeric expressions to numeric Numeric expressions can be used as the input for ramp in combination with numeric palettes. Linear interpolation will be used to generate intermediate output values.

Parameters
Name Description
input Number | Category

The input expression to give a color

palette Palette | Color Array | Number Array

The color palette that is going to be used

Returns
Number | Color
Example Mapping categories to colors and numbers
1
2
3
4
5
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.ramp(s.buckets(s.prop('dn'), [20, 50, 120]), [1, 4, 8])
  color: s.ramp(s.buckets(s.prop('dn'), [20, 50, 120]), s.palettes.PRISM)
});
CLICK TO COPY
Example Mapping categories to colors and numbers
1
2
3
4
const viz = new carto.Viz(`
  width: ramp(buckets($dn, [20, 50, 120]), [1, 10,4])
  color: ramp(buckets($dn, [20, 50, 120]), prism)
`);
CLICK TO COPY
Example Mapping numeric expressions to colors and numbers
1
2
3
4
5
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.ramp(s.linear(s.prop('dn'), 40, 100), [1, 8])
  color: s.ramp(s.linear(s.prop('dn'), 40, 100), s.palettes.PRISM)
});
CLICK TO COPY
Example Mapping numeric expressions to colors and numbers
1
2
3
4
const viz = new carto.Viz(`
  width: ramp(linear($dn, 40, 100), [1, 10,4])
  color: ramp(linear($dn, 40, 100), prism)
`);
CLICK TO COPY

reverse ( x )

Reverse the provided item.

Parameters
Name Description
x Palette | BaseArray

item to be reversed

Returns
Palette | BaseArray
Example Invert a Palette.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.prop('type'), s.reverse(s.palettes.PRISM));
});
CLICK TO COPY
No String example available
Example Invert a Palette .
1
2
3
const viz = new carto.Viz(`
  color: ramp($type, reverse(PRISM))
`);
CLICK TO COPY
Example Invert a Color Array.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.prop('count'), s.reverse([s.namedColor('red'), s.namedColor('blue')]));
});
CLICK TO COPY
No String example available
Example Invert a Color Array .
1
2
3
const viz = new carto.Viz(`
  color: ramp($count, reverse([red, blue]))
`);
CLICK TO COPY

rgb ( r , g , b )

Evaluates to a rgb color.

Parameters
Name Description
r Number

The amount of red in the color in the [0, 255] range. Numeric expression.

g Number

The amount of green in the color in the [0, 255] range. Numeric expression.

b Number

The amount of blue in the color in the [0, 255] range. Numeric expression.

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.rgb(0, 0, 255)
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: rgb(0, 0, 255)
`);
CLICK TO COPY

rgba ( r , g , b , a )

Evaluates to a rgba color.

Parameters
Name Description
r Number

The amount of red in the color in the [0, 255] range. Numeric expression.

g Number

The amount of green in the color in the [0, 255] range. Numeric expression.

b Number

The amount of blue in the color in the [0, 255] range. Numeric expression.

a Number

The alpha value of the color in the [0, 1] range. Numeric expression.

Returns
Color
Example Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.rgba(0, 0, 255, 1)
});
CLICK TO COPY
Example Display blue points.
1
2
3
const viz = new carto.Viz(`
  color: rgba(0, 0, 255, 1)
`);
CLICK TO COPY

scale ( width , zoomlevel )

Scale a width value to keep feature width constant in real space (meters). This will change the width in pixels at different zoom levels to enforce the previous condition.

Parameters
Name Description
width Number

pixel width at zoom level zoomlevel

zoomlevel Number

zoomlevel at which width is relative to

Returns
Number
Example Keep feature width in meters constant with 25 pixels at zoom level 7.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.scaled(25, 7)
});
CLICK TO COPY
Example Keep feature width in meters constant with 25 pixels at zoom level 7.
1
2
3
const viz = new carto.Viz(`
  width: s.scaled(25, 7)
`);
CLICK TO COPY

sign ( x )

Compute the sign of a number x, indicating whether the number is positive, negative or zero This means this function will return 1 if the number is positive, -1 if the number is negative 0 if the number is 0 and -0 if the number is -0.

Parameters
Name Description
x Number

Numeric expression to compute the sign

Returns
Number
Example Sign.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.sign(100)  // 1
});
CLICK TO COPY
Example Sign.
1
2
3
const viz = new carto.Viz(`
  width: sign(100)
`);
CLICK TO COPY

sin ( x )

Compute the sine of a number x.

Parameters
Name Description
x Number

Numeric expression to compute the sine in radians

Returns
Number
Example Sin.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.sin(Math.PI/2)  // 1
});
CLICK TO COPY
Example Sin.
1
2
3
const viz = new carto.Viz(`
  width: sin(PI/2)
`);
CLICK TO COPY

sqrt ( x )

Compute the square root of a number x.

Parameters
Name Description
x Number

Numeric expression to compute the square root

Returns
Number
Example Square root.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.sqrt(4)  // 2
});
CLICK TO COPY
Example Square root.
1
2
3
const viz = new carto.Viz(`
  width: sqrt(4)
`);
CLICK TO COPY

sub ( minuend , subtrahend )

Substract two numeric expressions.

Parameters
Name Description
minuend Number | Color

The minuend of the subtraction

subtrahend Number | Color

The subtrahend of the subtraction

Returns

Result of the substraction

Number | Color
Example Number subtraction.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.sub(10, 2)  // 8
});
CLICK TO COPY
Example Number subtraction.
1
2
3
const viz = new carto.Viz(`
  width: 10 - 2  // Equivalent to sub(10, 2)
`);
CLICK TO COPY

tan ( x )

Compute the tangent of a number x.

Parameters
Name Description
x Number

Numeric expression to compute the tangent in radians

Returns
Number
Example Tan.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.tan(0)  // 0
});
CLICK TO COPY
Example Tan.
1
2
3
const viz = new carto.Viz(`
  width: tan(0)
`);
CLICK TO COPY

time ( date )

Time contant expression

Parameters
Name Description
date Date | string

The date from a JavaScript Date() object or encoded as a string

Returns
Date
Example Filter by a date between dates.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.between(s.prop('date'), s.time('2022-03-09T00:00:00Z'), s.time('2033-08-12T00:00:00Z')
});
CLICK TO COPY
Example Filter by a date between dates.
1
2
3
const viz = new carto.Viz(`
  filter: time('2022-03-09T00:00:00Z') < $date < time('2033-08-12T00:00:00Z')
`);
CLICK TO COPY

top ( property , n )

Get the top n properties, aggregating the rest into an "others" bucket category.

Parameters
Name Description
property Category

Column of the table

n number

Number of top properties to be returned, the maximum value is 16, values higher than that will result in an error

Returns
Category
Example Use top 3 categories to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.top(s.prop('category'), 3), s.palettes.VIVID)
});
CLICK TO COPY
Example Use top 3 categories to define a color ramp.
1
2
3
const viz = new carto.Viz(`
  color: ramp(top($category, 3), VIVID)
`);
CLICK TO COPY

transition ( duration )

Transition returns a number from zero to one based on the elapsed number of milliseconds since the viz was instantiated. The animation is not cyclic. It will stick to one once the elapsed number of milliseconds reach the animation's duration.

Parameters
Name Description
duration number

Animation duration in milliseconds

Returns
Number

var ( name )

Alias to a named variable defined in the Viz.

Parameters
Name Description
name string

The variable name that is going to be evaluated

Returns
Number | Category | Color | Date
Example
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
    sum_price: s.clusterSum(s.prop('price'))
  }
 filter: s.neq(s.var('sum_price'), 'london')
});
CLICK TO COPY
Example
1
2
3
4
const viz = new carto.Viz(`
  @sum_price: clusterSum($price)
  filter: $price == 30  // Equivalent to eq($price, 30)
`);
CLICK TO COPY

viewportAvg ( input )

Return the average value of an expression for the features showed in the viewport (features outside the viewport and features that don't pass the filter will be excluded).

Parameters
Name Description
input Number

numeric expression

Returns

Result of the aggregation

Number
Example Assign the average of the `amount` property in the viewport to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     v_avg: s.viewportAvg(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the average of the `amount` property in the viewport to a variable.
1
2
3
const viz = new carto.Viz(`
  @v_avg: viewportAvg($amount)
`);
CLICK TO COPY

viewportCount ( input )

Return the feature count of the features showed in the viewport (features outside the viewport and features that don't pass the filter will be excluded).

Parameters
Name Description
input Number

numeric expression

Returns

Result of the aggregation

Number
Example Assign the feature count in the viewport to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     v_count: s.viewportCount(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the feature count in the viewport to a variable.
1
2
3
const viz = new carto.Viz(`
  @v_count: viewportCount($amount)
`);
CLICK TO COPY

viewportEqIntervals ( input , n )

Classify input by using the equal intervals method with n buckets.

It will classify the input based on the filtered dataset, filtering by viewport and by filter .

Parameters
Name Description
input Number

The input expression to classify

n number

Number of buckets

Returns
Category
Example Use viewport equal intervals to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.viewportEqIntervals(s.prop('density'), 5), s.palettes.PRISM)
});
CLICK TO COPY
Example Use viewport equal intervals to define a color ramp.
1
2
3
const viz = new carto.Viz(`
  color: ramp(viewportEqIntervals($density, 5), PRISM)
`);
CLICK TO COPY

viewportFeatures ( properties )

Generates a list of features in the viewport

For each feature, the properties specified as arguments to this expression will be available. Filtered features will not be present in the list. This expression cannot be used for rendering, it can only be used in JavaScript code as in the example below.

Parameters
Name Description
properties

properties that will appear in the feature list

Returns

ViewportFeatures

ViewportFeatures
Example Define and use a list of features.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const source = carto.source.Dataset('data');
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
    list: s.viewportFeatures(s.prop('value'), s.prop('category'))
  }
});
const layer = carto.Layer('layer', source, viz);
...

layer.on('updated', () => {
  viz.variables.list.value.forEach(feature => {
    console.log('value:', feature.value, 'category:', feature.category);
  });
});
CLICK TO COPY
Example Define and use a list of features.
1
2
3
4
5
6
7
8
9
10
11
12
const source = carto.source.Dataset('data');
const viz = new carto.Viz(`
  @list: viewportFeatures($value, $category)
`);
const layer = carto.Layer('layer', source, viz);
...

layer.on('updated', () => {
  viz.variables.list.value.forEach(feature => {
    console.log('value:', feature.value, 'category:', feature.category);
  });
});
CLICK TO COPY

viewportMax ( input )

Return the maximum value of an expression for the features showed in the viewport (features outside the viewport and features that don't pass the filter will be excluded).

Parameters
Name Description
input Number

numeric expression

Returns

Result of the aggregation

Number
Example Assign the maximum of the `amount` property in the viewport to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     v_max: s.viewportMax(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the maximum of the `amount` property in the viewport to a variable.
1
2
3
const viz = new carto.Viz(`
  @v_max: viewportMax($amount)
`);
CLICK TO COPY

viewportMin ( input )

Return the minimum value of an expression for the features showed in the viewport (features outside the viewport and features that don't pass the filter will be excluded).

Parameters
Name Description
input Number

numeric expression

Returns

Result of the aggregation

Number
Example Assign the minimum of the `amount` property in the viewport to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     v_min: s.viewportMin(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the minimum of the `amount` property in the viewport to a variable.
1
2
3
const viz = new carto.Viz(`
  @v_min: viewportMin($amount)
`);
CLICK TO COPY

viewportPercentile ( input , percentile )

Return the Nth percentile of an expression for the features showed in the viewport (features outside the viewport and features that don't pass the filter will be excluded).

Parameters
Name Description
input Number

Numeric expression

percentile Number

Numeric expression [0, 100]

Returns

Result of the aggregation

Number
Example Assign the percentile of the `amount` property in the viewport to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     v_percentile: s.viewportPercentile(s.prop('amount'), 90)
  }
});
CLICK TO COPY
Example Assign the percentile of the `amount` property in the viewport to a variable.
1
2
3
const viz = new carto.Viz(`
  @v_percentile: viewportPercentile($amount, 90)
`);
CLICK TO COPY

viewportQuantiles ( input , n )

Classify input by using the quantiles method with n buckets.

It will classify the input based on the filtered dataset, filtering by viewport and by filter .

Parameters
Name Description
input Number

The input expression used in the quantiles

n number

Number of buckets to be returned

Returns
Category
Example Use viewportQuantiles to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  color: s.ramp(s.viewportQuantiles(s.prop('density'), 5), s.palettes.PRISM)
});
CLICK TO COPY
Example Use viewportQuantiles to define a color ramp.
1
2
3
const viz = new carto.Viz(`
  color: ramp(viewportQuantiles($density, 5), PRISM)
`);
CLICK TO COPY

viewportSum ( input )

Return the sum of an expression for the features showed in the viewport (features outside the viewport and features that don't pass the filter will be excluded).

Parameters
Name Description
input Number

numeric expression

Returns

Result of the aggregation

Number
Example Assign the sum of the `amount` property in the viewport to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
  variables: {
     v_sum: s.viewportSum(s.prop('amount'))
  }
});
CLICK TO COPY
Example Assign the sum of the `amount` property in the viewport to a variable.
1
2
3
const viz = new carto.Viz(`
  @v_sum: viewportSum($amount)
`);
CLICK TO COPY

width

Return the expression assigned in the width property. ONLY usable in an order: property.

Note: ordering expressions won't assure a perfect ordering. Features will be distributed in different buckets with the original order, and those buckets will be ordered. This guarantees a maximum error, but not a perfect order. For most operations this is imperceptible, but usage of order in combination with animation or multi-scale expressions ( zoomrange and scaled ) may result in artifacts.

Returns
carto.expressions.Width
Example Ascending order based on width.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  order: s.asc(s.width())
});
CLICK TO COPY
Example Ascending order based on width.
1
2
3
const viz = new carto.Viz(`
  order: asc(width())
`);
CLICK TO COPY

zoom

Get the current zoom level.

Returns
Number
Example Only show feature at zoom levels less than 7.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  filter: s.lt(s.zoom(), 7)
});
CLICK TO COPY
Example Only show feature at zoom levels less than 7.
1
2
3
const viz = new carto.Viz(`
  filter: zoom() < 7
`);
CLICK TO COPY

zoomrange ( zoomBreakpointList )

Define a list of interpolated zoom ranges based on an input breakpoint list. Useful in combination with ramp (see examples).

Parameters
Name Description
zoomBreakpointList Number Array

list of zoom breakpoints with at least two elements

Returns
Number
Example Set the width to 1 at zoom levels < 7, set the width at 20 at zoom levels > 10, interpolate between 1 and 20 at zoom levels in the [7,10] range.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
  width: s.ramp(s.zoomrange([7, 10]), [1, 20])
});
CLICK TO COPY
Example Set the width to 1 at zoom levels < 7, set the width at 20 at zoom levels > 10, interpolate between 1 and 20 at zoom levels in the [7,10] range.
1
2
3
const viz = new carto.Viz(`
  width: width: ramp(zoomrange([7, 10]), [1, 20])
`);
CLICK TO COPY

carto.expressions.Animation

Animation class

This class is instanced automatically by using the animation function. It is documented for its methods.

Type
class

Extends

carto.source.Base

Methods

getProgressPct

Get the animation progress.

Returns

A number representing the progress. 0 when the animation just started and 1 at the end of the cycle.

Number

getProgressValue

Get the current time stamp of the animation

Returns

Current time stamp of the animation. If the animation is based on a numeric expression this will output a number, if it is based on a date expression it will output a date

Number | Date
Example Using the `getProgressValue` method to get the animation current value.
1
2
3
4
5
6
7
8
9
10
11
const s = carto.expressions;
let animationExpr = s.animation(s.linear(s.prop('saledate'), 1991, 2017), 20, s.fade(0.7, 0.4));
const animationStyle = {
  color: s.ramp(s.linear(s.prop('priceperunit'), 2000, 1010000), [s.rgb(0, 255, 0), s.rgb(255, 0, 0)]),
  width: s.mul(s.sqrt(s.prop('priceperunit')), 0.05),
  filter: animationExpr
};
layer.on('updated', () => {
  let currTime = Math.floor(animationExpr.getProgressValue());
  document.getElementById('timestamp').innerHTML = currTime;
});
CLICK TO COPY
No String example available

pause

Pause the animation

play

Play/resume the animation

setCurrent ( value )

Set the time stamp of the animation

Parameters
Name Description
value Date | number

A JavaScript Date object with the new animation time

setProgressPct ( progress )

Set the animation progress from 0 to 1.

Parameters
Name Description
progress number

A number in the [0-1] range setting the animation progress.

stop

Stops the animation

carto.expressions.Base

Abstract expression class

All expressions listed in carto.expressions inherit from this class so any of them can be used where an Expression is required as long as the types match.

This means that you can't use a numeric expression where a color expression is expected.

Type
class

Methods

blendTo ( final , duration , blendFunc )

Linear interpolation between this and finalValue with the specified duration

Parameters
Name Description
final Expression | string

Viz Expression or string to parse for a Viz expression

duration Expression

duration of the transition in milliseconds

blendFunc Expression

carto.Interactivity

Interactivity purpose is to allow the reception and management of user-generated events, like clicking, over layer features.

To create a Interactivity object an array of carto.Layer is required. Events fired from interactivity objects will refer to the features of these layers and only these layers. Moreover, the order of the features in the events will be determined by the order of the layers in this list.

Type
class
Options
Name Description
layerList carto.Layer | carto.Layer Array

carto.Layer or array of carto.Layer , events will be fired based on the features of these layers. The array cannot be empty, and all the layers must be attached to the same map.

options
Name Description
options.autoChangePointer boolean

A boolean flag indicating if the cursor should change when the mouse is over a feature.

Default: true

Example
1
2
3
4
5
const interactivity = new carto.Interactivity(layer);
interactivity.on('click', event => {
  style(event.features);
  show(event.coordinates);
});
CLICK TO COPY
No String example available

Events

featureClick

featureClick events are fired when the user clicks on features. The list of features behind the cursor is provided.

Type
FeatureEvent

featureClickOut

featureClickOut events are fired when the user clicks outside a feature that was clicked in the last featureClick event. The list of features that were clicked before and that are no longer behind this new click is provided.

Type
FeatureEvent

featureHover

featureHover events are fired when the user moves the cursor. The list of features behind the cursor is provided.

Type
FeatureEvent

featureEnter

featureEnter events are fired when the user moves the cursor and the movement implies that a non-previously hovered feature (as reported by featureHover or featureLeave) is now under the cursor. The list of features that are now behind the cursor and that weren't before is provided.

Type
FeatureEvent

featureLeave

featureLeave events are fired when the user moves the cursor and the movement implies that a previously hovered feature (as reported by featureHover or featureEnter) is no longer behind the cursor. The list of features that are no longer behind the cursor and that were before is provided.

Type
FeatureEvent

Methods

off ( eventName , callback )

Remove an event handler for the given type.

Parameters
Name Description
eventName string

Type of event to unregister

callback function

Handler function to unregister

on ( eventName , callback )

Register an event handler for the given type.

Parameters
Name Description
eventName string

Type of event to listen for

callback function

Function to call in response to given event, function will be called with a carto.FeatureEvent

carto.Layer

A Layer is the primary way to visualize geospatial data.

To create a layer a source and viz are required:

  • The source is used to know what data will be displayed in the Layer.

  • The viz is used to know how to draw the data in the Layer, Viz instances can only be bound to one single layer.

Type
class
Options
Name Description
id string

The ID of the layer. Can be used in the addTo function

source carto.source.Base

The source of the data

viz carto.Viz

The description of the visualization of the data

Example
1
const layer = new carto.Layer('layer0', source, viz);
CLICK TO COPY
No String example available

Events

Methods

addTo ( map , beforeLayerID )

Add this layer to a map. If the map's style is not loaded yet it will wait for it to add the layer as soon as possible.

Parameters
Name Description
map mapboxgl.Map

The map on which to add the layer

beforeLayerID

The ID of an existing layer to insert the new layer before. If this values is not passed the layer will be added on the top of the existing layers.

blendToViz ( viz , ms , interpolator , duration )

Blend the current viz with another viz.

This allows smooth transforms between two different vizs.

Parameters
Name Description
viz carto.Viz

The final viz

ms
interpolator
duration number

The animation duration in milliseconds

Example Smooth transition variating point size
1
2
3
4
5
6
7
8
9
// We create two different vizs varying the width
const viz0 = new carto.Viz({ width: 10 });
const viz1 = new carto.Viz({ width: 20 });
// Create a layer with the first viz
const layer = new carto.Layer('layer', source, viz0);
// We add the layer to the map, the points in this layer will have widh 10
layer.addTo(map, 'layer0');
// The points will be animated from 10px to 20px for 500ms.
layer.blendToViz(viz1, 500);
CLICK TO COPY
No String example available

hide

Change layer visibility to hidden

off ( eventName , callback )

Remove an event handler for the given type.

Parameters
Name Description
eventName string

Type of event to unregister

callback function

Handler function to unregister

on ( eventName , callback )

Register an event handler for the given event name. Valid names are: loaded , updated .

Parameters
Name Description
eventName string

Type of event to listen for

callback function

Function to call in response to given event

remove

Remove this layer from the map. It should be called after the layer is loaded. Otherwise, it will not delete the layer.

show

Change layer visibility to visible

update ( source , viz )

Update the layer with a new Source and a new Viz object, replacing the current ones. The update is done atomically, i.e.: the viz will be changed with the source, not before it. This method will return a promise that will be resolved once the source and the visualization are validated. The promise will be rejected if the validation fails, for example because the visualization expects a property name that is not present in the source. The promise will be rejected also if this method is invoked again before the first promise is resolved. If the promise is rejected the layer's source and viz won't be changed.

Parameters
Name Description
source carto.source.Base

The new Source object

viz

Optional. The new Viz object

carto.source.Base

Base data source object.

The methods listed in the carto.source.Base object are available in all source objects.

Use a source to reference the data used in a layer .

carto.source.Base should not be used directly use carto.source.Dataset , carto.source.SQL of carto.source.GeoJSON instead.

Type
class

carto.source.Dataset

A dataset defines the data that will be displayed in a layer and is equivalent to a table in the server.

If you have a table named european_cities in your CARTO account you could load all the data in a layer using a carto.source.Dataset .

If you want to load data applying a SQL query see carto.source.SQL .

Since tables in the server are protected you must provide valid credentials in order to get access to the data. This can be done setting the default auth in the carto object or providing an auth object with your username and apiKey.

If your server is not hosted by CARTO you must add a third parameter that includes the serverURL. This can be done setting the default config in the carto object or providing a config object with your serverURL.

The combination of different type of geometries on the same source is not supported. Valid geometry types are points , lines and polygons .

Type
class
Options
Name Description
tableName string

The name of an existing table

auth
Name Description
auth.apiKey string

API key used to authenticate against CARTO

auth.user string

Name of the user

config
Name Description
config.serverURL string

URL of the CARTO Maps API server

Default: 'https://{user}.carto.com'

Extends

carto.source.Base
Example
1
2
3
4
const source = new carto.source.Dataset('european_cities', {
  apiKey: 'YOUR_API_KEY_HERE',
  user: 'YOUR_USERNAME_HERE'
});
CLICK TO COPY
No String example available

Events

carto.source.GeoJSON

Create a carto.source.GeoJSON source from a GeoJSON object.

Type
class
Options
Name Description
data object

A GeoJSON data object

options
Name Description
options.dateColumns string array

List of columns that contain dates.

The combination of different type of geometries on the same source is not supported. Valid geometry types are Point , LineString , MultiLineString , Polygon and MultiPolygon .

Extends

carto.source.Base
Example
1
2
3
4
5
6
7
8
9
10
const source = new carto.source.GeoJSON({
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [ 0, 0 ]
  },
  "properties": {
    "index": 1
  }
});
CLICK TO COPY
No String example available

Events

carto.source.SQL

A SQL defines the data that will be displayed in a layer.

Imagine you have a table named european_cities and you only want to download data from european cities with population > 100000

				const source = new carto.source.SQL(`SELECT * FROM european_cities WHERE country like 'europe' AND population > 10000`, {
  apiKey: 'YOUR_API_KEY_HERE',
  user: 'YOUR_USERNAME_HERE'
});
		

This only downloads the data you need from the server reducing data usage.

If you need all the data see carto.source.Dataset .

Since tables in the server are protected you must provide valid credentials in order to get access to the data. This can be done setting the default auth in the carto object or providing an auth object with your username and apiKey.

If your server is not hosted by CARTO you must add a third parameter that includes the serverURL. This can be done setting the default config in the carto object or providing a config object with your serverURL.

The combination of different type of geometries on the same source is not supported. Valid geometry types are points , lines and polygons .

Type
class
Options
Name Description
query string

A SQL query containing a SELECT statement

auth
Name Description
auth.apiKey string

API key used to authenticate against CARTO

auth.user string

Name of the user

config
Name Description
config.serverURL string

URL of the CARTO Maps API server

Default: 'https://{user}.carto.com'

Extends

carto.source.Base
Example
1
2
3
4
const source = new carto.source.SQL('SELECT * FROM european_cities', {
  apiKey: 'YOUR_API_KEY_HERE',
  user: 'YOUR_USERNAME_HERE'
});
CLICK TO COPY
No String example available

Events

CartoError

Represents an error in the carto library.

Properties
Name
Description
message string

A short error description

name string

The name of the error "CartoError"

origin string

Where the error was originated: 'validation'

originalError object

An object containing the internal/original error

stack object

Error stack trace

type string

Error type

Category

Type of Category Expressions.

Associated to expressions that return is a category string. When these expressions are evaluated it should return a JavaScript string.

JavaScript strings are automatically converted to Category Expressions.

Color

Type of Color Expressions.

Associated to expressions that return a color. When these expressions are evaluated it should return a RGBA object like:

				{ r: 255, g: 255, b: 255, a: 1.0 }
		

Date

Type of Date Expressions.

Fade

Type of Fade Expressions.

Feature

Feature objects are provided by FeatureEvent events.

Type
object
Properties
Name
Description
id number

Unique identification code

color FeatureVizProperty
width FeatureVizProperty
colorStroke FeatureVizProperty
widthStroke FeatureVizProperty
variables FeatureVizProperty Array

Declared variables in the viz object

reset function

Reset custom feature vizs by fading out duration milliseconds, where duration is the first parameter to reset

FeatureEvent

FeatureEvent objects are fired by Interactivity objects.

Type
object
Properties
Name
Description
coordinates object

LongLat coordinates in { lng, lat } form

position object

Pixel coordinates in { x, y } form

features Feature Array

Array of Feature

FeatureVizProperty

FeatureVizProperty objects can be accessed through Feature objects.

Type
object
Properties
Name
Description
blendTo function

Change the feature viz by blending to a destination viz expression expr in duration milliseconds, where expr is the first parameter and duration the last one

reset function

Reset custom feature viz property by fading out duration milliseconds, where duration is the first parameter to reset

value function

Getter that evaluates the property and returns the computed value

LayerEvent

LayerEvent objects are fired by Layer objects.

Type
object

MVTMetadata

An MVTMetadata object declares metadata information of a a carto.Source.

Type
object
Properties
Name
Description
properties MVTProperty

property names, types and optionally ranges

idProperty

property name of the property that should be used as ID

Example Creating a MVTMetadata object
1
2
3
4
5
6
7
const metadata = {
properties: {
numfloors: { type: 'number' },
cartodb_id: { type: 'number' }
},
idProperty: 'cartodb_id',
};
CLICK TO COPY
No String example available

MVTOptions

A MVTOptions object declares a MVT configuration

Type
object
Properties
Name
Description
layerID string

layerID on the MVT tiles to decode, the parameter is optional if the MVT tiles only contain one layer

viewportZoomToSourceZoom

function to transform the viewport zoom into a zoom value to replace {z} in the MVT URL template, undefined defaults to Math.ceil

maxZoom number

limit MVT tile requests to this zoom level, undefined defaults to no limit

Example Use layer `myAwesomeLayer` and request tiles up to zoom level 12.
1
2
3
4
const options = {
    layerID: 'myAwesomeLayer',
    maxZoom: 12
};
CLICK TO COPY
No String example available
Example Use layer `myAwesomeLayer` and request tiles only at zoom levels 4, 5 and 6.
1
2
3
4
const options = {
    layerID: 'myAwesomeLayer',
    viewportZoomToSourceZoom: zoom => Math.min(Math.max(Math.ceil(zoom), 4), 6)
};
CLICK TO COPY
No String example available
Example Use layer `myAwesomeLayer` and request tiles only at zoom levels 0,3,6,9...
1
2
3
4
const options = {
    layerID: 'myAwesomeLayer',
    viewportZoomToSourceZoom: zoom => Math.round(zoom / 3) * 3
};
CLICK TO COPY
No String example available

MVTProperty

MVTProperty objects declare a property type and, optionally, additional information like numeric ranges.

Type
object
Properties
Name
Description
type string

Valid values are 'number' and 'category', 'category' must be used if the MVT encodes the property as strings, regardless of the real type

min Number

With type='number' min specifies the minimum value in the dataset, this is used in global aggregation expressions

max Number

With type='number' max specifies the maximum value in the dataset, this is used in global aggregation expressions

Number

Type of Numeric Expressions.

Associated to expressions that return is an integer or float. When these expressions are evaluated it should return a JavaScript number.

JavaScript numbers are automatically converted to Numeric Expressions.

Palette

Type of Palette Expressions.

More information in carto.expressions.palettes .

VizSpec

A vizSpec object is used to create a Viz and controlling multiple aspects. For a better understanding we recommend reading the Introduction to Expressions guide

Type
object
Properties
Name
Description
color Color

fill color of points and polygons and color of lines, if used with symbol the color will override the original image RGB channels

width Number

fill diameter of points, thickness of lines, not applicable to polygons

strokeColor Color

stroke/border color of points and polygons, not applicable to lines

strokeWidth Number

stroke width of points and polygons, not applicable to lines

filter Number

filter features by removing from rendering and interactivity all the features that don't pass the test. In combination with carto.expressions.animation temporal maps can be created.

symbol Image

show an image instead in the place of points. There is a list of built-in icons you can use by default in the Icons section

symbolPlacement Placement

when using symbol , offset to apply to the image

offset Placement

offset to apply to the features in pixels

order Order

rendering order of the features, only applicable to points. See carto.expressions.asc , carto.expressions.desc and carto.expressions.noOrder

resolution number

resolution of the property-aggregation functions, only applicable to points. Default resolution is 1. Custom values must be greater than 0 and lower than 256. A resolution of N means points are aggregated to grid cells NxN pixels. Unlinke Torque resolution , the aggregated points are placed in the centroid of the cluster, not in the center of the grid cell.

variables object

An object describing the variables used.