The CARTO VL functionality is exposed through the carto namespace including:
Current version:
Setup:
CARTO Basemaps:
Source:
Layer:
Viz:
Expressions:
Interactivity:
The version of CARTO VL in use as specified in
package.json
and the GitHub release.
Remove an event handler for the given event name, layer list and callback.
eventName |
String
event |
layerList |
carto.Layer
List of layers |
callback |
function
Handler function to unregister |
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.
eventName |
String
Supported event names are 'loaded' and 'updated' |
layerList |
carto.Layer
Array
List of layers |
callback |
Set default authentication parameters: [user or username] and apiKey.
auth |
|
Set default configuration parameters
config |
|
Use CARTO basemaps for your map visualization. Here you have more information about our basemaps .
Dark-Matter vector basemap
Example
Use Dark-Matter vector basemap.
1
2
3
4
const map = new mapboxgl.Map({
container: 'map',
style: carto.basemaps.darkmatter
})
Example
Use Dark-Matter vector basemap.
1
2
3
4
const map = new mapboxgl.Map({
container: 'map',
style: carto.basemaps.darkmatter
})
Positron vector basemap
Example
Use Positron vector basemap.
1
2
3
4
const map = new mapboxgl.Map({
container: 'map',
style: carto.basemaps.positron
})
Example
Use Positron vector basemap.
1
2
3
4
const map = new mapboxgl.Map({
container: 'map',
style: carto.basemaps.positron
})
Voyager vector basemap
Example
Use Voyager vector basemap.
1
2
3
4
const map = new mapboxgl.Map({
container: 'map',
style: carto.basemaps.voyager
})
Example
Use Voyager vector basemap.
1
2
3
4
const map = new mapboxgl.Map({
container: 'map',
style: carto.basemaps.voyager
})
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:
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.
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:
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.
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.
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 .
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);
});
Example
Using a color scheme.
1
2
3
const viz = new carto.Viz(`
color: ramp($type, PRISM)
`);
Use discretised property as aggregate dimension. This operation disables the access to the property
except within
clusterTime
expressions with the same parameters.
Note:
clusterTime
can only be created with a
carto.expressions.prop
,
as the first parameter, not other expressions.
When the units of resolution are cyclic periods such as 'dayOfWeek' (day of the week) or 'monthOfYear' (month of the year), the resulting expression takes a numeric value to represent the period, e.g. 1 for Monday or January.
When the units are not cyclic (e.g. 'week' or 'month'), the resulting expression is a
TimeRange
that
encompass each individual calendar period, for example week 2018-W03 (third week of 2018 from 2018-01-15 to 2018-01-21)
or 2018-03 (March 2018, from 2018-03-01 to 2018-04-01).
Accepted values for cyclic resolution periods are:
semesterOfYear
(6-month term) takes values from 1 to 2
trimesterOfYear
(4-month term) takes values from 1 to 3
quarterOfYear
(3-month term) takes values from 1 to 4
monthOfYear
takes values from 1 (January) to 12 (December)
weekOfYear
follows
ISO 8601 numbering
taking values from 1 up to 53
dayOfWeek
(as per ISO 8601, 1 = Monday, to 7 = Sunday
dayOfMonth
takes values from 1 to 31
dayOfYear
takes values from 1 to 366
hourOfDay
takes values from 0 to 23
minuteOfHour
takes values from 0 to 59
Accepted values for serial resolution units are:
year
, e.g. '2017'
month
, e.g. '2017-03'
day
, e.g. '2017-03-01'
hour
, e.g. '2017-03-01T13'
minute
, e.g. '2017-03-01T13:22'
second
, e.g. '2017-03-01T13:22:31'
week
represented as '2018-W03' (third week of 2018:, 2018-01-15 to 2018-01-21)
quarter
as '2018-Q2' (second quarter of 2018, i.e. 2018-04 to 2018-06)
semester
as '2018S2' (second semester of 2018, i.e. 2018-07 to 2018-12)
trimester
as '2018t2' (second trimester of 2018, i.e. 2018-05 to 2018-08)
decade
as 'D201' (decade 201, i.e. 2010 to 2019)
century
as 'C21' (21st century, ie. 2001 to 2100)
millennium
as 'M3' (3rd millennium: 2001 to 3000)
The time zone is optional. By default UTC time will be used.
It admits a fixed offset from UTC as a signed number of seconds,
or
IANA
timezone
names
such as
America/New_York
or
Europe/Madrid
, which not only define a time offset,
but also rules for DST (daylight savings time).
property |
Date
Column of the table to be discretised as dimension |
units |
String
Units of resolution for the discretization |
timezone |
String
Time zone in which the dates are discretised. UTC by default. |
Dimension column; takes time range values (intervals) for serial units of resolutions and numbers for recurrent units.
TimeRange
|
Number
Example
Use months as a dimension of the cluster aggregations as `month`.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
month: s.clusterTime(s.prop('date', 'month', 'America/New_York'))
});
Example
Use months as a dimension of the cluster aggregations as `month`.
1
2
3
const viz = new carto.Viz(`
month: clusterTime($date, 'month', 'America/New_York')
`);
Define a time range: an interval between two time points.
ISO-formatted strings (based on ISO 8601) are used to define ranges.
Since
timeRange
doesn't support arbitrary intervals, but only
intervals based on single units of time (e.g. a month, an hour),
we don't use the general ISO interval format, but simply an
abbreviated form of the date point format, so that '2018-03' represents
the month of March, 2018 (i.e. the interval 2018-03-01T00:00:00/2018-04-01T00:00:00).
value |
String
abbreviated ISO-formatted interval |
It retuns a TimeRange object.
TimeRange
Example
Abs.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.abs(-100) // 100
});
Example
Abs.
1
2
3
const viz = new carto.Viz(`
width: abs(-100) // 100
`);
Example
Number addition.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.add(10, 2) // 12
});
Example
Number addition.
1
2
3
const viz = new carto.Viz(`
width: 10 + 2 // Equivalent to add(10, 2)
`);
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))
input |
Color
input color to normalize |
normalizer |
Number
numeric property that will be used to normalize the input color |
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')
)
});
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
)
});
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
.
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')
)
});
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'))
`);
Create an animated temporal filter (animation). Read more about the Animation Class
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
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 |
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))
});
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))
`);
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))
});
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
6
7
8
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))
`);
Animation class
This class is instanced automatically by using the `animation` function. It is documented for its methods.
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.
by |
carto.expressions.Width
must be
|
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())
});
Example
Ascending order based on width.
1
2
3
const viz = new carto.Viz(`
order: asc(width())
`);
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
.
input |
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 |
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);
});
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)
`);
Linearly interpolate from
a
to
b
based on
mix
.
a |
Number
|
Color
Numeric or color expression,
|
b |
Number
|
Color
Numeric or color expression,
|
mix |
Number
Numeric expression with the interpolation parameter in the [0,1] range |
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))
);
});
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)
)
`);
Given a property create "sub-groups" based on the given breakpoints.
This returns a number or category expression depending on the input values.
property |
Number
|
Category
The property to be evaluated and interpolated |
breakpoints |
Number Array
|
Category Array
Expression containing the different breakpoints. |
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
)
});
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)
`);
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)
)
});
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)
`);
Example
Color by $city using the CARTOColor Prism by assigning different color in Prism to each category.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.categoryIndex(s.prop('city')), s.palettes.PRISM)
});
Example
Color by $city using the CARTOColor Prism by assigning different color in Prism to each category.
1
2
3
const viz = new carto.Viz(`
color: ramp(categoryIndex($city), PRISM)
`);
Example
Ceil.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.ceil(5.1); // 6
});
Example
Ceil.
1
2
3
const viz = new carto.Viz(`
width: ceil(5.1)
`);
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)
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: cielab(32.3, 79.2, -107.86)
`);
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.
property |
Number
Column of the table to be aggregated |
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'))
});
Example
Use cluster average of the population as width.
1
2
3
const viz = new carto.Viz(`
width: clusterAvg($population)
`);
Count of features per cluster.
Note:
clusterCount
has no input parameters and if data is not aggregated, it always returns 1
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
});
Example
Use cluster count for width.
1
2
3
const viz = new carto.Viz(`
width: clusterCount() / 50
`);
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.
property |
Number
Column of the table to be aggregated |
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'))
});
Example
Use cluster maximum of the population as width.
1
2
3
const viz = new carto.Viz(`
width: clusterMax($population)
`);
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.
property |
Number
Column of the table to be aggregated |
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'))
});
Example
Use cluster minimum of the population as width.
1
2
3
const viz = new carto.Viz(`
width: clusterMin($population)
`);
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.
property |
Category
Column of the table to be aggregated |
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)
});
Example
Use cluster mode of the population in a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(clusterMode($category), PRISM)
`);
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.
property |
Number
Column of the table to be aggregated |
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'))
});
Example
Use cluster sum of the population as width.
1
2
3
const viz = new carto.Viz(`
width: clusterSum($population)
`);
Wraps a constant number. Implies a GPU optimization vs number expression .
x |
number
A number to be warped in a constant numeric expression |
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)
});
Example
Creating a constant number expression.
1
2
3
const viz = new carto.Viz(`
width: constant(15)
`);
Example
Cos.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.cos(0) // 1
});
Example
Cos.
1
2
3
const viz = new carto.Viz(`
width: cos(0)
`);
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.
by |
carto.expressions.Width
must be
|
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())
});
Example
Descending order based on width.
1
2
3
const viz = new carto.Viz(`
order: desc(width())
`);
Example
Number division.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.div(10, 2) // 5
});
Example
Number division.
1
2
3
const viz = new carto.Viz(`
width: 10 / 2 // Equivalent to div(10, 2)
`);
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)
});
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)
`);
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))
});
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))
`);
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))
});
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))
`);
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))
});
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))
`);
Example
Floor.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.floor(5.9) // 5
});
Example
Floor.
1
2
3
const viz = new carto.Viz(`
width: floor(5.9)
`);
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.
property |
Number
property expression of number type |
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'))
}
});
Example
Assign the global average of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
@g_avg: globalAvg($amount)
`);
Example
Assign the global count of features to a variable.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
variables: {
g_count: s.globalCount()
}
});
No String example available
Example
Assign the global count of features.
1
2
3
const viz = new carto.Viz(`
@g_count: globalCount()
`);
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)
});
Example
Use global equal intervals to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(globalEqIntervals($density, 5), PRISM)
`);
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.
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'))
}
});
Example
Assign the global maximum of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
@g_max: globalMax($amount)
`);
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.
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'))
}
});
Example
Assign the global minimum of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
@g_min: globalMin($amount)
`);
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)
}
});
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)
`);
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.CB_REDS)
});
Example
Use global quantiles to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(globalQuantiles($density, 5), CB_REDS)
`);
Classify
input
by using the Mean-Standard Deviation method with
n
buckets.
It will classify the input based on the entire dataset without filtering by viewport or by
filter
.
It uses average and standard deviation (population formula) to classify the dataset. When using an odd number of buckets, the central class has a double size (classSize * 2), to honour the number of required buckets
This method is suitable if data are normally (or near normal) distributed, and it is specially appropiated for diverging datasets, which can be well displayed using a diverging color scheme like TEALROSE
input |
Number
The input expression to classify |
n |
number
Number of buckets |
classSize |
Optional. The class size, defaults to 1.0 standard deviation (usual values are also 0.5 or 0.25) |
Category
Example
Use global mean-standard deviation to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.globalStandardDev(s.prop('density'), 5), s.palettes.TEALROSE)
});
Example
Use global mean-standard deviation to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(globalStandardDev($density, 5), TEALROSE)
`);
Example
Use global custom mean-standard deviation to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.globalStandardDev(s.prop('density'), 7, 0.5), s.palettes.TEALROSE)
});
Example
Use global custom mean-standard deviation to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(globalStandardDev($density, 7, 0.5), TEALROSE)
`);
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.
property |
Number
property expression of number type |
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'))
}
});
Example
Assign the global sum of the `amount` property to a variable.
1
2
3
const viz = new carto.Viz(`
@g_sum: globalSum($amount)
`);
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)
});
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)
`);
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)
});
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)
`);
Create a color from its hexadecimal description.
hexadecimalColor |
String
Color in the #RGB, #RGBA, #RRGGBB or #RRGGBBAA format |
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'`
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: #00F // Equivalent to hex('#00F')
`);
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)
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: hsl(0.67, 1.0, 0.5)
`);
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)
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: hsla(0.67, 1.0, 0.5, 1.0)
`);
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)
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: hsv(0.67, 1.0, 1.0)
`);
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)
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: hsva(0.67, 1.0, 1.0, 1.0)
`);
Image. Load an image and use it as a symbol.
Note: image RGB color will be overridden if the viz
color
property is set.
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')
});
Example
Load a svg image.
1
2
3
const viz = new carto.Viz(`
symbol: image('./marker.svg')
`);
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'])
});
Example
Display only cities where $type is 'metropolis' or 'capital'.
1
2
3
const viz = new carto.Viz(`
filter: $type in ['metropolis', 'capital']
`);
Example
Filter NULL values of the `numeric` property.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
filter: s.not(s.isNull(s.prop('numeric')))
});
Example
Filter NULL values of the `numeric` property.
1
2
3
const viz = new carto.Viz(`
filter: not(isNull($numeric))
`);
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)
.
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 |
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)
});
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)
`);
Wrapper around arrays. Explicit usage is unnecessary since CARTO VL will wrap implicitly all arrays using this function.
When used with Transformation expressions, the returned value will be a Transformation that will chain each single transformation one after another.
elements |
Number Array
|
Category Array
|
Color Array
|
Date Array
|
Image Array
|
Transform Array
|
List
|
Transform
Example
Rotate then translate.
1
2
3
4
5
const s = carto.expressions;
const viz = new carto.Viz({
symbol: s.CROSS
transform: [s.rotate(90), s.translate(10, 20)]
});
Example
Rotate then translate.
1
2
3
4
const viz = new carto.Viz(`
symbol: cross
transform: [rotate(90), translate(10, 20)]
`);
Example
Natural Logarithm.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.log(10) // 2.302585092994046
});
Example
Natural Logarithm.
1
2
3
const viz = new carto.Viz(`
width: log(10)
`);
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)
});
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)
`);
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)
});
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)
`);
Example
Number modulus.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.mod(10, 6) // 4
});
Example
Number modulus.
1
2
3
const viz = new carto.Viz(`
width: 10 % 6 // Equivalent to mod(10, 6)
`);
Example
Number multiplication.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.mul(5, 5) // 25
});
Example
Number multiplication.
1
2
3
const viz = new carto.Viz(`
width: 5 * 5 // Equivalent to mul(5, 5)
`);
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'`
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: blue // Equivalent to namedColor('blue')
`);
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);
});
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)
`);
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'])
});
Example
Display only cities where $type is not 'metropolis' or 'capital'.
1
2
3
const viz = new carto.Viz(`
filter: $type nin ['metropolis', 'capital']
`);
Example
No order.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
order: s.noOrder()
});
Example
No order.
1
2
3
const viz = new carto.Viz(`
order: noOrder()
`);
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
x |
Number
Number to compute the not value |
Number
Example
Not.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.not(0) // 1
});
Example
Not.
1
2
3
const viz = new carto.Viz(`
width: not(0)
`);
Get the current timestamp. This is an advanced form of animation,
animation
expression is preferred.
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)
});
Example
Update width during the time.
1
2
3
const viz = new carto.Viz(`
width: now() % 10
`);
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)`
});
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)`
`);
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
.
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)
)
});
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))
`);
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.
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)
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. |
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)
});
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)
`);
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.
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
});
Example
Number power.
1
2
3
const viz = new carto.Viz(`
width: 2 ^ 3 // Equivalent to pow(2, 3)
`);
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.
name |
String
The property in the dataset that is going to be evaluated |
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')
});
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'
`);
Create a ramp: a mapping between an input (numeric or categorical) and an output (number, colors and/or images)
When the input has the same number of categories (without taking the "others" category into account). Then, each input category will have a one to one match with an output value.
Some case examples:
ramp(buckets($product, ['A, 'B', 'C']), [house, car, bus])
ramp(buckets($price, [20, 50, 120]), [1, 10, 4, 12])
ramp(top($product, 3), [blue, yellow, green])
ramp(globalQuantiles($price, 3), [red, yellow, green])
When the input has different number of categories or the input is a linear expression. Then it will interpolate the output values (Note: this is not supported if output values are images)
Some case examples:
ramp(linear($price, 1, 10) [green, yellow, red])
`ramp(buckets($product, ['A, 'B', 'C'], [red, blue]))
When the input is a categorical property, we wrap it automatically in a CategoryIndex expression
ramp($product, Prism)
(equivalent to
ramp($categoryIndex($product)), Prism)
When the input is a numeric property, we wrap it automatically in a Linear expression.
ramp($price, Prism)
(equivalent to
ramp($linear($price)), Prism)
The "others" value is setted by default, depending on the output type:
If it is "Number", the "others" value is 1.
If it is "Color" from a color array (i.e: [red, yellow, green]), the "others" value is the gray color.
If it is "Color" from a cartocolor palette (i.e: Prism), the "others" value is the last color of the palette.
If it is "Image", the "others" value is a circle.
If we add a third parameter, the "others" default value will be overridden by this one
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 |
others |
(Optional) Value that overrides the default value for "others" |
Number
|
Color
|
Image
Example
Mapping categories to numbers, colors and images.
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
width: s.ramp(s.buckets(s.prop('product'), ['A, 'B', 'C']), [1, 2, 3])
color: s.ramp(s.buckets(s.prop('product'), ['A, 'B', 'C']), s.palettes.PRISM)
strokeColor: s.ramp(s.buckets(s.prop('product'), ['A, 'B', 'C']), [s.namedColor('red'), s.namedColor('yellow'), s.namedColor('green')])
symbol: s.ramp(s.buckets(s.prop('product'), ['A, 'B', 'C']), [s.HOUSE, s.CAR, s.BUS])
});
Example
Mapping categories to numbers, colors and images.
1
2
3
4
5
6
const viz = new carto.Viz(`
width: ramp(buckets($product), ['A, 'B', 'C']), [1, 2, 3])
color: ramp(buckets($product), ['A, 'B', 'C']), Prism)
strokeColor: ramp(buckets($product), ['A, 'B', 'C']), [red, yellow, green])
symbol: ramp(buckets($product), ['A, 'B', 'C']), [house, car, bus])
`);
Example
Mapping classified numeric properties to numbers, colors and images.
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
width: s.ramp(s.buckets(s.prop('price'), [40, 100]), [1, 2, 3])
color: s.ramp(s.buckets(s.prop('price'), [40, 100]), s.palettes.PRISM)
strokeColor: s.ramp(s.buckets(s.prop('price'), [40, 100]), [s.namedColor('red'), s.namedColor('yellow'), s.namedColor(green)])
symbol: s.ramp(s.buckets(s.prop('price'), [40, 100]), [s.HOUSE), s.CAR, s.BUS])
});
Example
Mapping classified numeric properties to numbers, colors and images.
1
2
3
4
5
6
const viz = new carto.Viz(`
width: ramp(buckets($price, [40, 100]), [1, 2, 3])
color: ramp(buckets($price, [40, 100]), Prism)
strokeColor: ramp(buckets($price, [40, 100]), [red, yellow, green])
symbol: ramp(buckets($price, [40, 100]), [house, car, bus])
`);
Example
Override default values.
1
2
3
4
5
6
7
const s = carto.expressions;
const viz = new carto.Viz({
width: s.ramp(s.top(s.prop('price'), 3), [1, 2, 3], 0)
strokeColor: s.ramp(s.top(s.prop('price'), 3), Prism, s.namedColor('red'))
color: s.ramp(s.top(s.prop('price'), 3), [s.namedColor('blue'), s.namedColor('red'), s.namedColor('yellow')], s.namedColor(black))
symbol: s.ramp(s.top(s.prop('price'), 3), [s.HOUSE, s.CAR, s.BUS], s.CROSS)
});
Example
Override default values.
1
2
3
4
5
6
const viz = new carto.Viz(`
width: ramp(top($price, 3), [1, 2, 3], 0)
strokeColor: ramp(top($price, 3), Prism, red)
color: ramp(top($price, 3), [blue, red, yellow], black)
symbol: ramp(top($price, 3), [house, car, bus], cross)
`);
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));
});
No String example available
Example
Invert a Palette .
1
2
3
const viz = new carto.Viz(`
color: ramp($type, reverse(PRISM))
`);
Example
Invert a List.
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')]));
});
No String example available
Example
Invert a List .
1
2
3
const viz = new carto.Viz(`
color: ramp($count, reverse([red, blue]))
`);
Evaluates to a rgb color.
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. |
Color
Example
Display blue points.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
color: s.rgb(0, 0, 255)
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: rgb(0, 0, 255)
`);
Evaluates to a rgba color.
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. |
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)
});
Example
Display blue points.
1
2
3
const viz = new carto.Viz(`
color: rgba(0, 0, 255, 1)
`);
Rotate. Define a rotation in degrees.
Limitation: only supported in combination with
symbol:
.
angle |
Number
angle to rotate in degrees in clockwise direction |
Transform
Example
Rotate 30 degrees in clockwise direction.
1
2
3
4
5
const s = carto.expressions;
const viz = new carto.Viz({
symbol: s.CROSS
transform: s.rotate(30)
});
Example
Rotate 30 degrees in clockwise direction.
1
2
3
4
const viz = new carto.Viz(`
symbol: cross
transform: rotate(30)
`);
Example
Rotate 30 degrees in counter-clockwise direction.
1
2
3
4
5
const s = carto.expressions;
const viz = new carto.Viz({
symbol: s.CROSS
transform: s.rotate(-30)
});
Example
Rotate 30 degrees in counter-clockwise direction.
1
2
3
4
const viz = new carto.Viz(`
symbol: cross
transform: rotate(-30)
`);
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.
width |
Number
pixel width at zoom level
|
zoomlevel |
Number
zoomlevel at which
|
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)
});
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)
`);
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.
x |
Number
Numeric expression to compute the sign |
Number
Example
Sign.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.sign(100) // 1
});
Example
Sign.
1
2
3
const viz = new carto.Viz(`
width: sign(100)
`);
Example
Sin.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.sin(Math.PI/2) // 1
});
Example
Sin.
1
2
3
const viz = new carto.Viz(`
width: sin(PI/2)
`);
Example
Square root.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.sqrt(4) // 2
});
Example
Square root.
1
2
3
const viz = new carto.Viz(`
width: sqrt(4)
`);
Example
Number subtraction.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.sub(10, 2) // 8
});
Example
Number subtraction.
1
2
3
const viz = new carto.Viz(`
width: 10 - 2 // Equivalent to sub(10, 2)
`);
Example
Tan.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
width: s.tan(0) // 0
});
Example
Tan.
1
2
3
const viz = new carto.Viz(`
width: tan(0)
`);
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')
});
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')
`);
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)
});
Example
Use top 3 categories to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(top($category, 3), VIVID)
`);
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.
duration |
number
Animation duration in milliseconds |
Number
Translate. Define a translation:
x |
number
first numeric expression that indicates the translation in the X direction. |
y |
number
second numeric expression that indicates the translation in the Y direction. |
Numeric expression
Translate
Example
Apply an x, y translation
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
transform: s.translate(10, 20)
});
No String example available
Example
Apply an x, y translation.
1
2
3
const viz = new carto.Viz(`
transform: translate(10, 20)
`);
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')
});
Example
1
2
3
4
const viz = new carto.Viz(`
@sum_price: clusterSum($price)
filter: $price == 30 // Equivalent to eq($price, 30)
`);
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'))
}
});
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)
`);
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).
feature count in the viewport
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()
}
});
Example
Assign the feature count in the viewport to a variable.
1
2
3
const viz = new carto.Viz(`
@v_count: viewportCount()
`);
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)
});
Example
Use viewport equal intervals to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(viewportEqIntervals($density, 5), PRISM)
`);
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.
properties |
properties that will appear in the feature list |
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);
});
});
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);
});
});
Generates a 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.
input |
Number
expression to base the histogram |
size |
Number
Optional (defaults to 20). Number of bars to use if
|
weight |
Number
Optional. Weight each occurrence differently based on this weight, defaults to
|
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, 3, 1)
`);
...
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
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'))
}
});
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)
`);
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'))
}
});
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)
`);
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).
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)
}
});
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)
`);
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)
});
Example
Use viewportQuantiles to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(viewportQuantiles($density, 5), PRISM)
`);
Classify
input
by using the Mean-Standard Deviation method with
n
buckets.
It will classify the input based on the filtered dataset, filtering by viewport and by
filter
.
It uses average and standard deviation (population formula) to classify the dataset. When using an odd number of buckets, the central class has a double size (classSize * 2), to honour the number of required buckets
This method is suitable if data are normally (or near normal) distributed, and it is specially appropiated for diverging datasets, which can be well displayed using a diverging color scheme like TEALROSE
input |
Number
The input expression to classify |
n |
number
Number of buckets |
classSize |
Optional. The class size, defaults to 1.0 standard deviation (usual values are also 0.5 or 0.25) |
Category
Example
Use viewport mean-standard deviation to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.viewportStandardDev(s.prop('density'), 5), s.palettes.TEALROSE)
});
Example
Use viewport mean-standard deviation to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(viewportStandardDev($density, 5), tealrose)
`);
Example
Use viewport custom mean-standard deviation to define a color ramp.
1
2
3
4
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.viewportStandardDev(s.prop('density'), 7, 0.5), s.palettes.TEALROSE)
});
Example
Use viewport custom mean-standard deviation to define a color ramp.
1
2
3
const viz = new carto.Viz(`
color: ramp(viewportStandardDev($density, 7, 0.5), tealrose)
`);
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'))
}
});
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)
`);
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.
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())
});
Example
Ascending order based on width.
1
2
3
const viz = new carto.Viz(`
order: asc(width())
`);
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)
});
Example
Only show feature at zoom levels less than 7.
1
2
3
const viz = new carto.Viz(`
filter: zoom() < 7
`);
Define a list of interpolated zoom ranges based on an input breakpoint list. Useful in combination with ramp (see examples).
zoomBreakpointList |
Number Array
list of zoom breakpoints with at least two elements |
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])
});
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])
`);
Interactivity purpose is to allow the reception and management of user-generated events, like clicking, over layer features.
To create a Interactivity object a carto.Layer or an array with several carto.Layer is required. Events fired from interactivity objects will refer to the features of these layer/s and only these layer/s. Moreover, when using an array of layers, the order of the features in the events will be determined by the order of these layers in the layerList.
class
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 |
|
Example
1
2
3
4
5
const interactivity = new carto.Interactivity(layer);
interactivity.on('click', event => {
style(event.features);
show(event.coordinates);
});
No String example available
featureClick events are fired when the user clicks on features. The list of features behind the cursor is provided.
FeatureEvent
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.
FeatureEvent
featureHover events are fired when the user moves the cursor. The list of features behind the cursor is provided.
FeatureEvent
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.
FeatureEvent
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.
FeatureEvent
Remove an event handler for the given type.
eventName |
String
Type of event to unregister |
callback |
function
Handler function to unregister |
Register an event handler for the given type.
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 |
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.
class
id |
String
The ID of the layer. Can be used in the addTo function |
source |
carto.source
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);
No String example available
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.
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. |
Blend the current viz with another viz.
This allows smooth transitions between two different Vizs.
Blending won't be performed when convenient for the attached Source. This happens with Maps API sources when the new Viz uses a different set of properties or aggregations. In these cases a hard transition will be used instead.
This method returns a promise that will be resolved if validations passed.
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 viz won't be changed by this call.
Concurrent calls to
update
will override the effects of
blendToViz
:
if a call to
blendToViz
is performed after a call to
update
, but the
update
hasn't been resolved yet,
the call to
update
will override the call to
blendToViz
is it resolves.
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);
No String example available
Change layer visibility to hidden
Remove an event handler for the given type.
eventName |
String
Type of event to unregister. Valid names are:
|
callback |
function
Handler function to unregister |
Register an event handler for the given event name.
eventName |
String
Type of event to listen for. Valid names are:
|
callback |
function
Function to call in response to given event |
Remove this layer from the map. It should be called after the layer is loaded. Otherwise, it will not delete the layer.
Change layer visibility to visible
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 by this call.
Concurrent calls to
blendToViz
or
blendTo
won't override calls to update (like calls to
update
do).
source |
carto.source
The new Source object. |
viz |
Optional. The new Viz object. Defaults to the current viz. |
Layer visibility property.
Viz attached to this layer.
Calls to
blendToViz
and
update
won't update the viz until those calls "commit",
having performed and completed all asynchronous necessary sanity checks.
Base data source object.
The current sources available are: Dataset , SQL , GeoJSON and MVT
Use a source to reference the data used in a layer .
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
.
tableName |
String
The name of an existing table |
||||||
auth |
|
||||||
config |
|
Example
1
2
3
4
const source = new carto.source.Dataset('european_cities', {
apiKey: 'YOUR_API_KEY_HERE',
username: 'YOUR_USERNAME_HERE'
});
No String example available
Create a carto.source.GeoJSON source from a GeoJSON object.
data |
Object
A GeoJSON data object |
||||
options |
|
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
}
});
No String example available
Create a carto.source.MVT.
templateURL |
string
|
string Array
A string with the URL template of the MVT tiles in https://mytileserver.com/{z}/{x}/{y}.mvt format or a list of such templates. Usage of a list of templates with different domains is recommended since that allows the browser to make more requests in parallel. |
metadata |
(Optional) Metadata of the source, declaring property name, types and optionally ranges. |
options |
(Optional) MVT source configuration, the default value will be valid for regular URL templates if the tiles are composed of only one layer
The combination of different type of geometries on the same source is not supported. Valid geometry types are
|
Example
1
2
3
4
5
6
7
8
9
10
11
// Usage with multiple templateURLs as recommended
const metadata = new carto.source.mvt.Metadata([{ type: 'number', name: 'total_pop'}])
const source = new carto.source.MVT(
[
"https://server-a.tileserver.com/{z}/{x}/{y}.mvt",
"https://server-b.tileserver.com/{z}/{x}/{y}.mvt",
"https://server-c.tileserver.com/{z}/{x}/{y}.mvt",
"https://server-d.tileserver.com/{z}/{x}/{y}.mvt"
],
metadata
);
No String example available
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
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
.
query |
String
A SQL query containing a SELECT statement |
||||||
auth |
|
||||||
config |
|
Example
1
2
3
4
const source = new carto.source.SQL('SELECT * FROM european_cities', {
apiKey: 'YOUR_API_KEY_HERE',
username: 'YOUR_USERNAME_HERE'
});
No String example available
Class TimeRange represents an interval of time between to instants.
Only single unit-of-time intervals such as a calender year, month, day, hour, etc. are supported, arbitrary intervals are not.
A TimeRange can be defined and accessed either by its start and end instants
or by an abbreviated ISO-formatted textual representation.
For the text format, since general intervals are not supported, the ISO interval
format is not used, but simply the abbreviated form of the time unit.
For example, to represent March 2018,
2018-03
is used instead of the
ISO-formatted interval
018-03-01T00:00:00/2018-04-01T00:00:00
.
A TimeRange includes its start instant and excludes the end instant: it represents the semi-open interval start <= t < end.
class
A Viz is one of the core elements of CARTO VL and defines how the data will be styled, displayed and processed. A Viz instance can only be bound to one layer.
class
definition |
string
|
vizSpec
The definition of a viz. This parameter could be a
|
Example
Create a viz with black dots using the string constructor
1
2
3
const viz = new carto.Viz(`
color: rgb(0,0,0)
`);
No String example available
Example
Create a viz with black dots using the vizSpec constructor
1
2
3
const viz = new carto.Viz({
color: carto.expressions.rgb(0,0,0)
});
No String example available
Get the geometry type of the visualization.
Stringify the visualization
String
Represents an error in the carto library.
Name |
Description |
---|---|
message |
String
A short error description |
name |
String
The name of the error "CartoError" |
originalError |
Object
An object containing the internal/original error |
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.
Type of Color Expressions.
Associated to expressions that return a color. When these expressions are evaluated it should return a RGBA object like:
Constant ALIGN_BOTTOM translation. Equivalent to
carto.expressions.translate(0, 1)
.
Read more about translation in
carto.expressions.translate
Constant ALIGN_CENTER translation. Equivalent to
carto.expressions.translate(0, 0)
.
Read more about translation in
carto.expressions.translate
Constant E number.
Constant FALSE value. Equivalent to
carto.expressions.constant(0)
Constant HOLD number. Max Safe Integer number to be used to "hold" the Fade expression. Read more about fading in carto.expressions.fade
Constant PI number.
Constant TRUE value. Equivalent to
carto.expressions.constant(1)
CARTO VL Expression
An expression is a function that is used to modify the visualization. All expressions are listed in carto.expressions .
Any expression 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.
class
Linear interpolate between
this
and
final
with the specified duration
final |
Expression
|
string
Viz Expression or string to parse for a Viz expression |
duration |
Expression
duration of the transition in milliseconds |
blendFunc |
Expression
|
true
if the evaluation of the expression may change without external action,
false
otherwise.
Get the expression stringified
Stringified expression
String
Example
Get the stringified expression of the viz color property.
1
2
3
4
5
6
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.linear('amount'), s.palettes.PRISM)
});
console.log(viz.color.toString());
// logs: "ramp(linear($amount), Prism)"
Example
Get the stringified expression of the viz color property.
1
2
3
4
5
6
const viz = new carto.Viz(`
color: ramp(linear($amount), Prism)
`);
console.log(viz.color.toString());
// logs: "ramp(linear($amount), Prism)"
Animation class
This class is instanced automatically by using the
animation
function. It is documented for its methods.
class
Get the animation progress.
A number representing the progress. 0 when the animation just started and 1 at the end of the cycle.
Number
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;
});
No String example available
Pause the animation
Play/resume the animation
Set the time stamp of the animation
value |
Date
|
number
A JavaScript Date object with the new animation time |
Set the animation progress from 0 to 1.
progress |
number
A number in the [0-1] range setting the animation progress. |
Stops the animation
Ramp Class
A mapping between an input (numeric or categorical) and an output (number, colors and/or images)
This class is instanced automatically by using the
ramp
function. It is documented for its methods.
Read more about ramp expression at
carto.expressions.ramp
.
class
Get a legend for the ramp.
Note: This method works only for feature property independent outputs. Example:
This works:
ramp($price, [5, 15])
This does not work:
ramp($price, [5, $amount])
config |
|
{ type, data }
. 'type' could be category or number. Data is an array of { key, value } objects. 'key' depends on the expression type. 'value' is the result evaluated by the ramp. There is more information in the examples.
Object
Example
Get legend for a color ramp of a categorical property.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.prop('vehicles'), s.palettes.PRISM)
});
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData();
// legend = {
// type: 'category',
// name: '$vehicles',
// data: [
// { key: 'Bicycle', value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: 'Car', value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: 'Bus', value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: 'CARTO_VL_OTHERS', value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend for a color ramp of a categorical property.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const viz = new carto.Viz(`
color: ramp($vehicles, PRISM)
´);
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData();
// legend = {
// type: 'category',
// name: '$vehicles',
// data: [
// { key: 'Bicycle', value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: 'Car', value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: 'Bus', value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: 'CARTO_VL_OTHERS', value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend for an image ramp of a categorical property.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const s = carto.expressions;
const viz = new carto.Viz({
symbol: s.ramp(s.prop('vehicles'), [s.BICYCLE, s.CAR, s.BUS])
});
layer.on('loaded', () => {
const legend = layer.viz.symbol.getLegendData();
// legend = {
// type: 'category',
// name: '$vehicles',
// data: [
// { key: 'Bicycle', value: bicycleImageUrl },
// { key: 'Car', value: carImageUrl },
// { key: 'Bus', value: busImageUrl },
// { key: 'CARTO_VL_OTHERS', value: circleImageUrl }
// ]
// }
});
Example
Get legend for an image ramp of a categorical property.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const viz = new carto.Viz(`
symbol: ramp('$vehicles'), [BICYCLE, CAR, BUS])
`);
layer.on('loaded', () => {
const legend = layer.viz.symbol.getLegendData();
// legend = {
// type: 'category',
// name: '$vehicles',
// data: [
// { key: 'Bicycle', value: bicycleImageUrl },
// { key: 'Car', value: carImageUrl },
// { key: 'Bus', value: busImageUrl },
// { key: 'CARTO_VL_OTHERS', value: circleImageUrl }
// ]
// }
});
Example
Get legend of a ramp top expression and set "others" label.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.top(s.prop('vehicles')), s.palettes.PRISM)
});
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData({
othersLabel: 'Other Vehicles'
});
// legend = {
// type: 'category',
// name: 'top($vehicles)',
// data: [
// { key: 'Bicycle', value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: 'Car', value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: 'Bus', value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: 'Other Vehicles', value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend of a ramp top expression and set "others" label.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const viz = new carto.Viz(`
color: ramp(top($vehicles, 5), PRISM)
`);
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData({
othersLabel: 'Other Vehicles'
});
// legend = {
// type: 'category',
// name: 'top($vehicles)',
// data: [
// { key: 'Bicycle', value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: 'Car', value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: 'Bus', value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: 'Other Vehicles', value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend for a linear ramp expression and set number of samples.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.linear(s.prop('numvehicles'), 1, 100), s.palettes.PRISM)
});
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData({
samples: 4
});
// legend = {
// type: 'number',
// name: 'linear($numvehicles, 1, 100)',
// data: [
// { key: 25, value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: 50, value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: 75, value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: 100, value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend for a linear ramp expression and set number of samples.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const viz = new carto.Viz(`
color: ramp(linear($numvehicles, 1, 100), PRISM)
`);
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData({
samples: 4
});
// legend = {
// type: 'number',
// name: 'linear($numvehicles, 1, 100)',
// data: [
// { key: 25, value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: 50, value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: 75, value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: 100, value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend for a buckets ramp expression.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.buckets((s.prop('numvehicles'), [1, 2, 3]), s.palettes.PRISM))
});
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData();
// legend = {
// type: 'number',
// name: 'buckets($numvehicles, [1, 2, 3])',
// data: [
// { key: [-Infinity, 1], value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: [1, 2], value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: [2, 3], value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: [3, +Infinity], value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend for a buckets ramp expression.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const s = carto.expressions;
const viz = new carto.Viz(`
color: ramp(buckets($numvehicles', [1, 2, 3]), Prism))
`);
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData();
// legend = {
// type: 'number',
// name: 'buckets($numvehicles, [1, 2, 3])',
// data: [
// { key: [-Infinity, 1], value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: [1, 2], value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: [2, 3], value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: [3, +Infinity], value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend for a classifier ramp expression.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const s = carto.expressions;
const viz = new carto.Viz({
color: s.ramp(s.globalEqIntervals(s.prop('numvehicles'), 4), s.palettes.PRISM)
});
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData();
// legend = {
// type: 'number',
// name: 'globalEqIntervals($numvehicles, 4)',
// data: [
// { key: [-Infinity, 25], value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: [25, 50], value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: [50, 75], value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: [100, +Infinity], value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
Example
Get legend for a classifier ramp expression.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const s = carto.expressions;
const viz = new carto.Viz(`
color: ramp(globalEqIntervals($numvehicles, 4), Prism)
`);
layer.on('loaded', () => {
const legend = layer.viz.color.getLegendData();
// legend = {
// type: 'number',
// name: 'globalEqIntervals($numvehicles, 4)',
// data: [
// { key: [-Infinity, 25], value: { r: 95, g: 70, b: 144, a: 1 } },
// { key: [25, 50], value: { r: 29, g: 105, b: 150, a: 1 } },
// { key: [50, 75], value: { r: 56, g: 166, b: 165, a: 1 } },
// { key: [100, +Infinity], value: { r: 15, g: 133, b: 84, a: 1 } }
// ]
// }
});
ViewportHistogram Class
Generates a histogram.
This class is instanced automatically by using the
viewportHistogram
function. It is documented for its methods.
Read more about viewportHistogram expression at
carto.expressions.viewportHistogram
.
class
Get an array of joined data by key and sorted by frequency.
Note: It can be combined with a
ramp.getLegendData()
method. Take a look at the examples to see how it works.
values |
Array
Array of { key, value } pairs |
{ frequency, key, value }
Array
Example
Get joined data for a categorical property sorted by frequency.
1
2
3
4
5
6
7
8
const numberOfWheels = [
{ key: 'car', value: 4 },
{ key: 'truck', value: 8 },
{ key: 'bike', value: 2 }
];
const s = carto.expressions;
const viz = new carto.Viz({
Example
Get joined data for a categorical property sorted by frequency.
1
2
3
4
5
6
7
8
const numberOfWheels = [
{ key: 'car', value: 4 },
{ key: 'truck', value: 8 },
{ key: 'bike', value: 2 }
];
const s = carto.expressions;
const viz = new carto.Viz(`
Example
Get color values for the histogram when using a ramp.
1
2
const s = carto.expressions;
const viz = new carto.Viz(`
Example
Get color values for the histogram when using a ramp.
1
2
const s = carto.expressions;
const viz = new carto.Viz(`
Feature objects are provided by FeatureEvent events.
Object
Name |
Description |
---|---|
id |
number
Unique identification code |
color |
FeatureVizProperty
|
width |
FeatureVizProperty
|
colorStroke |
FeatureVizProperty
|
widthStroke |
FeatureVizProperty
|
symbol |
FeatureVizProperty
|
symbolPlacement |
FeatureVizProperty
|
filter |
FeatureVizProperty
|
transform |
FeatureVizProperty
|
variables |
FeatureVizProperty Array
Declared variables in the viz object |
reset |
function
Reset custom feature vizs by fading out
|
FeatureEvent objects are fired by Interactivity objects.
Object
Name |
Description |
---|---|
coordinates |
Object
LongLat coordinates in { lng, lat } form |
position |
Object
Pixel coordinates in { x, y } form |
features |
Feature Array
Array of Feature |
CARTO VL Features are objects that contain information of the visualization.
FeatureVizProperty objects can be accessed through Feature objects.
Object
Name |
Description |
---|---|
blendTo |
function
Change the feature viz by blending to a destination viz expression
|
reset |
function
Reset custom feature viz property by fading out
|
value |
function
Getter that evaluates the property and returns the computed value |
Constant BICYCLE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant BUILDING icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant BUS icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant CAR icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant CIRCLE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant CIRCLE_OUTLINE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant CROSS icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant FLAG icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant HOUSE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant MARKER icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant MARKER_OUTLINE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant SQUARE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant SQUARE_OUTLINE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant STAR icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant STAR_OUTLINE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant TRIANGLE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
Constant TRIANGLE_OUTLINE icon. Read more about how to use constant icons in carto.expressions.image . They can also be used in an array, as it is shown in carto.expressions.ramp . There is a list with all the default icons available.
bicycle |
building |
bus |
---|---|---|
car |
circle |
circleOutline |
cross |
flag |
house |
marker |
markerOutline |
plus |
square |
squareOutline |
star |
starOutline |
triangle |
triangleOutline |
An MVTMetadata object declares metadata information of a a carto.Source.
Object
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',
};
No String example available
A MVTOptions object declares a MVT configuration
Object
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
|
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
};
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)
};
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
};
No String example available
MVTProperty objects declare a property type and, optionally, additional information like numeric ranges.
Object
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
|
max |
Number
With
|
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.
Type of Ordered Expressions.
Order expressions are carto.expressions.asc , carto.expressions.desc and carto.expressions.noOrder .
Type of Placement expressions.
More information in carto.expressions.placement expression.
Type of Transformation expressions.
More information in carto.expressions.rotate and carto.expressions.translate expressions.
Depending on the output, each expression has a different type
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.
Type of Color Expressions.
Associated to expressions that return a color. When these expressions are evaluated it should return a RGBA object like:
Type of Date Expressions.
Type of Fade Expressions.
Type of Image Expressions.
More information in carto.expressions.image .
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.
Type of Ordered Expressions.
Order expressions are carto.expressions.asc , carto.expressions.desc and carto.expressions.noOrder .
Type of Palette Expressions.
More information in carto.expressions.palettes .
Type of Placement expressions.
More information in carto.expressions.placement expression.
Type of Transformation expressions.
More information in carto.expressions.rotate and carto.expressions.translate expressions.