Introduction

CARTO.js is a JavaScript library that interacts with different CARTO APIs. It is part of the CARTO Engine ecosystem.

To understand the fundamentals of CARTO.js 4.0, read the guides. To view the source code, browse the open-source repository in Github and contribute. Otherwise, view examples with Leaflet and Google Maps or find different support options.

If you find any trouble understanding any term written in this reference, please visit our glossary

The contents described in this document are subject to CARTO’s Terms of Service

Authentication

CARTO.js 4.0 requires using an API Key. From your CARTO dashboard, click Your API keys from the avatar drop-down menu to view your uniquely generated API Key for managing data with CARTO Engine.

Your API Keys

Learn more about the basics of authorization, or dig into the details of Auth API, if you want to know more about this part of CARTO platform.

The examples in this documentation include a placeholder for the API Key. Ensure that you modify any placeholder parameters with your own credentials. You will have to supply your unique API Key to a carto.Client.

1
2
3
4
var client = new carto.Client({
    apiKey: 'YOUR_API_KEY_HERE',
    username: 'YOUR_USERNAME_HERE'
});

Versioning

CARTO.js uses Semantic Versioning. View our Github repository to find tags for each release.

To get the version number programmatically, use carto.version.

1
2
console.log(carto.version);
// returns the version of the library

Loading the Library

CARTO.js is hosted on a CDN for easy loading. You can load the full source “carto.js” file or the minified version “carto.min.js”. Once the script is loaded, you will have a global carto namespace. CARTO.js is hosted in NPM as well. You can require it as a dependency in your custom apps.

1
2
3
4
5
<!-- CDN: load the latest CARTO.js version -->
<script src="https://cartodb-libs.global.ssl.fastly.net/carto.js/v4.0.0-beta/carto.min.js"></script>

<!-- CDN: load a specific CARTO.js version-->
<script src="https://cartodb-libs.global.ssl.fastly.net/carto.js/%VERSION%/carto.min.js"></script>
1
2
3
4
5
6
// NPM: load the latest CARTO.js version
npm install carto.js
// or
yarn add carto.js

var carto = require('carto.js');

Error Handling

Most of the errors fired by the library are handled by the client itself. The client will trigger a CartoError every time an error happens.

A cartoError is an object containing a single message field with a string explaining the error.

Some methods in CARTO.js are asynchronous. This means that they return a promise that will be fulfilled when the asynchronous work is done or rejected with a CartoError when an error occurs.

1
2
3
4
5
6
7
8
9
// All errors are passed to the client.
client.on(carto.events.ERROR, cartoError => {
    console.error(cartoError.message):
})

// .addLayer() is async.
client.addLayer(newLayer)
    .then(successCallback)
    .catch(errorCallback);

carto.ATTRIBUTION

ATTRIBUTION constant

© OpenStreetMap contributors, © CARTO

carto.Client

This is the entry point for a CARTO.js application.

A CARTO client allows managing layers and dataviews. Some operations like addding a layer or a dataview are asynchronous. The client takes care of the communication between CARTO.js and the server for you.

To create a new client you need a CARTO account, where you will be able to get your API key and username.

If you want to learn more about authorization and authentication, please read the authorization fundamentals section of our Developer Center.

Options
Name Description
settings
Name Description
settings.apiKey string

API key used to authenticate against CARTO

settings.username string

Name of the user

settings.serverUrl

URL of the windshaft server. Only needed in custom installations. Pattern:

string

(Optional)

Example
1
2
3
4
5
6
7
8
9
10
11
	var client = new carto.Client({
  apiKey: 'YOUR_API_KEY_HERE',
  username: 'YOUR_USERNAME_HERE'
});

var client = new carto.Client({
  apiKey: 'YOUR_API_KEY_HERE',
  username: 'YOUR_USERNAME_HERE',
  serverUrl: 'https://YOUR.CARTO.INSTANCE/user/YOUR_USERNAME_HERE'
});
	
CLICK TO COPY

Events

error

Fired when something went wrong on the server side.

Type
CartoError

success

Fired when a request to the server completed successfully.

Methods

addDataview ( dataview )

Add a dataview to the client.

Parameters
Name Description
dataview carto.dataview.Base

The dataview to be added

Returns

A promise that will be fulfilled when the dataview is added

Promise
Example
1
2
3
4
5
6
7
8
9
	// Add a dataview to the client
client.addDataview(dataview)
 .then(() => {
   console.log('Dataview added');
 })
 .catch(cartoError => {
   console.error(cartoError.message);
 }):
	
CLICK TO COPY

addDataviews ( dataviews )

Add multipe dataviews to the client.

Parameters
Name Description
dataviews

Array carto.dataview.Base

An array with the dataviews to be added

Returns

A promise that will be fulfilled when the dataviews are added

Promise
Example
1
2
3
4
5
6
7
8
9
	// Add several dataviews to the client
client.addDataview([dataview0, dataview1])
 .then(() => {
   console.log('Dataviews added');
 })
 .catch(cartoError => {
   console.error(cartoError.message);
 }):
	
CLICK TO COPY

addLayer ( layer )

Add a layer to the client. If the layer id already exists in the client this method will throw an error.

Parameters
Name Description
layer carto.layer.Base

The layer to be added

Returns

A promise that will be fulfilled when the layer is added

Promise
Example
1
2
3
4
5
6
7
8
9
	// Add a layer to the client
client.addLayer(layer)
 .then(() => {
   console.log('Layer added');
 })
 .catch(cartoError => {
   console.error(cartoError.message);
 });
	
CLICK TO COPY

addLayers ( layers )

Add multiple layers to the client at once.

Parameters
Name Description
layers

Array carto.layer.Base

An array with the layers to be added. Note that (

Returns

A promise that will be fulfilled when the layers are added

Promise
Example
1
2
3
4
5
6
7
8
9
	// Add multiple layers ad once layer to the client
client.addLayers([layer0, layer1])
 .then(() => {
   console.log('Layers added');
 })
 .catch(cartoError => {
   console.error(cartoError.message);
 });
	
CLICK TO COPY

getDataviews ( )

Get all the dataviews from the client.

Returns

An array with all the dataviews from the client

Array carto.dataview.Base
Example
1
2
3
	// Get all the dataviews from the client
const dataviews = client.getDataviews();
	
CLICK TO COPY

getGoogleMapsMapType ( map )

Return a google.maps.MapType that groups all the layers that have been added to this client.

Parameters
Name Description
map google.maps.Map

The native Google Maps map where the CARTO layers will be displayed.

Returns

A Google Maps mapType that groups all the layers: google.maps.MapType

google.maps.MapType
Example
1
2
3
	// Get googlemaps MapType from client
const gmapsMapType = client.getGoogleMapsMapType();
	
CLICK TO COPY
Example
1
2
3
	// Add googlemaps MapType to a google map
googleMap.overlayMapTypes.push(client.getGoogleMapsMapType(googleMap));
	
CLICK TO COPY

getLayers ( )

Get all the layers from the client.

Returns

An array with all the Layers from the client

Array carto.layer.Base
Example
1
2
3
	// Get all layers from the client
const layers = client.getLayers();
	
CLICK TO COPY
Example
1
2
3
	// Hide all layers from the client
client.getLayers().forEach(layer => layer.hide());
	
CLICK TO COPY

getLeafletLayer ( )

Return a leaflet layer that groups all the layers that have been added to this client.

Returns

A L.TileLayer layer that groups all the layers.

Example
1
2
3
	// Get the leafletlayer from the client
const cartoLeafletLayer = client.getLeafletLayer();
	
CLICK TO COPY
Example
1
2
3
	// Add the leafletLayer to a leafletMap
client.getLeafletLayer().addTo(map);
	
CLICK TO COPY

moveLayer ( layer , toIndex )

Move layer order.

Parameters
Name Description
layer carto.layer.Base

The layer to be moved

toIndex carto.layer.Base

The layer to be moved

Returns

A promise that will be fulfilled when the layer is moved

Promise
Example
1
2
3
4
5
6
7
8
9
	// Move layer order
client.moveLayer(layer1, 0)
.then(() => {
 console.log('Layer moved');
})
.catch(cartoError => {
 console.error(cartoError.message);
});
	
CLICK TO COPY

removeDataview ( dataview )

Remove a dataview from the client.

Parameters
Name Description
dataview carto.dataview.Base

The dataview array to be removed

Returns

A promise that will be fulfilled when the dataview is removed

Promise
Example
1
2
3
4
5
6
7
8
9
	// Remove a dataview from the client
client.removeDataview(dataview)
.then(() => {
   console.log('Dataviews removed');
 })
 .catch(cartoError => {
   console.error(cartoError.message);
 }):
	
CLICK TO COPY

removeLayer ( layer )

Remove a layer from the client.

Parameters
Name Description
layer carto.layer.Base

The layer to be removed

Returns

A promise that will be fulfilled when the layer is removed

Promise
Example
1
2
3
4
5
6
7
8
9
	// Remove a layer from the client
client.removeLayer(layer)
.then(() => {
 console.log('Layer removed');
})
.catch(cartoError => {
 console.error(cartoError.message);
});
	
CLICK TO COPY

removeLayers ( layers )

Remove multiple layers from the client.

Parameters
Name Description
layers

Array carto.layer.Base

An array with the layers to be removed

Returns

A promise that will be fulfilled when the layers are removed

Promise
Example
1
2
3
4
5
6
7
8
9
	// Remove multiple layers from the client
client.removeLayers([layer1, layer2])
.then(() => {
 console.log('Layers removed');
})
.catch(cartoError => {
 console.error(cartoError.message);
});
	
CLICK TO COPY

carto.dataview.Base

Base class for dataview objects.

Dataviews are a way to extract data from a CARTO account in predefined ways (eg: a list of categories, the result of a formula operation, etc.).

This object should not be used directly

The data used in a dataviews cames from a source that might change due to different reasons (eg: SQL query changed).

When dataview data changes the dataview will trigger events to notify subscribers when new data is available.

Example
1
2
3
4
5
	// Keep your widget data sync. Remember each dataview has his own data format.
dataview.on('dataChanged', newData => {
 renderWidget(newData);
})
	
CLICK TO COPY

Events

dataChanged

Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.

Type
carto.dataview.CategoryData
carto.dataview.FormulaData
carto.dataview.HistogramData
carto.dataview.TimeSeriesData

columnChanged

Fired when the column name has changed. Handler gets a parameter with the new column name.

Type
string

statusChanged

Fired when the status has changed. Handler gets a parameter with the new status.

Contains a single argument with the new status.

Type
carto.dataview.status

error

Fired when something went wrong on the server side.

Type
CartoError

Methods

addFilter ( filter )

Add a filter .

Parameters
Name Description
filter carto.filter.Base

Returns

this

carto.dataview.Base

disable ( )

Disable the dataview. This stops the dataview from fetching new data when there is a map change (like changing map configuration or changing map bounding box).

Returns

this

carto.dataview.Base

enable ( )

Enable the dataview. When enabled, a dataview fetches new data when the map changes (changing map configuration or changing map bounding box).

Returns

this

carto.dataview.Base

getColumn ( )

Return the current dataview column where the dataview is applied.

Returns

Current dataview column

string

getSource ( )

Return the current source where the dataview gets the data from.

Returns

Current source object

carto.source.Base

getStatus ( )

Return the current dataview status.

Returns

Current dataview status

carto.dataview.status

hasError ( )

Return true is the current status is error.

Returns
boolean

hasFilter ( filter )

Check if a filter exists in the dataview.

Parameters
Name Description
filter carto.filter.Base

Returns

this

carto.dataview.Base

isEnabled ( )

Return true if the dataview is enabled.

Returns
boolean

isLoaded ( )

Return true is the current status is loaded.

Returns
boolean

isLoading ( )

Return true is the current status is loading.

Returns
boolean

removeFilter ( filter )

Remove a filter .

Parameters
Name Description
filter carto.filter.Base

Returns

this

carto.dataview.Base

setColumn ( column )

Set the dataview column.

Parameters
Name Description
column string

Returns

this

carto.dataview.Base

carto.dataview.BinItem

Type
object
Properties
Name
Description
index number

Number indicating the bin order

start number

The lower limit of the bin

end number

The higher limit of the bin

min number

The minimal value appearing in the bin. Only appears if freq > 0

max number

The minimal value appearing in the bin. Only appears if freq > 0

avg number

The average value of the elements for this bin. Only appears if freq > 0

freq number

Number of elements in the bin

normalized number

Normalized frequency with respect to the whole data

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
	// We created an histogram containing airBnb prices per night
const histogramDataview = new carto.dataview.Histogram(airbnbDataset, 'price', { bins: 7 });
// Listen to dataChanged events
histogramDataview.on('dataChanged', data => { 
 // The first bin contains prices from 0 to 20€ per night, there are 3 rentals in this bin with a cost of 10 15 and 20€.
 const bin = console.log(data.bins[0]);
 // This is the bin index in the bins array
 bin.index; // 0
 // The first bin contains rentals from 0 to 20€ per night
 bin.start; // 0
 // The first bin contains rentals from 0 to 20€ per night
 bin.end; // 20
 // The lower rental in the bin is 10€ per night
 bin.min; // 10
 // The maximun rental in the bin is 20€ per night
 bin.max; // 20
 // The average price in this bin is 15€ per night
 bin.avg; // 15
 // The bin contains 3 prices
 bin.freq; // 3
 // Those 3 prices represent the 20% of the dataset.
 bin.normalized; // 0.2
});
	
CLICK TO COPY

carto.dataview.Category

A category dataview is used to aggregate data performing a operation.

This is similar to a group by SQL operation, for example:

				SELECT country, AVG(population) GROUP BY country
		

The following code is the CARTO.js equivalent:

				var categoryDataview = new carto.dataview.Category(citiesSource, 'country', {
    operation: carto.operation.AVG, // Compute the average
    operationColumn: 'population' // The name of the column where the operation will be applied.
 });
		

Like every other dataview, this is an async object and you must wait for the data to be availiable.

The data format for the category-dataview is described in carto.dataview.CategoryData

Options
Name Description
source carto.source.Base

The source where the dataview will fetch the data

column string

The name of the column used to create categories

options

(Optional)

Name Description
options.limit number

The maximum number of categories in the response

Default: 6

options.operation

The operation to apply to the data

carto.operation

(Optional)

options.operationColumn

The column where the operation will be applied

string

(Optional)

Extends

carto.dataview.Base
Example
1
2
3
4
5
6
7
	// From a cities dataset with name, country and population show the average city population per country:
var column = 'country'; // Aggregate the data by country.
var categoryDataview = new carto.dataview.Category(citiesSource, column, {
    operation: carto.operation.AVG, // Compute the average
    operationColumn: 'population' // The name of the column where the operation will be applied.
 });
	
CLICK TO COPY
Example
1
2
3
4
5
	// Listen for data updates
categoryDataview.on('dataChanged', newData => {
 console.log(newData); // CategoryData object
});
	
CLICK TO COPY
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
	// You can listen to multiple events emmited by the category-dataview.
categoryDataview.on('statusChanged', (newData, error) => { });
categoryDataview.on('error', cartoError => { });

// Listen to specific category-dataview events.
categoryDataview.on('columnChanged', newData => {
 console.log(newData); // 'population'
});
categoryDataview.on('limitChanged', newData => {
 console.log(newData); // 11
});
categoryDataview.on('operationChanged', newData => { });
categoryDataview.on('operationColumnChanged', newData => { });
	
CLICK TO COPY

Events

dataChanged

Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.

Type
carto.dataview.CategoryData
carto.dataview.FormulaData
carto.dataview.HistogramData
carto.dataview.TimeSeriesData

columnChanged

Fired when the column name has changed. Handler gets a parameter with the new column name.

Type
string

statusChanged

Fired when the status has changed. Handler gets a parameter with the new status.

Contains a single argument with the new status.

Type
carto.dataview.status

error

Fired when something went wrong on the server side.

Type
CartoError

limitChanged

Fired when limit has changed. Handler gets a parameter with the new limit.

Type
number

operationChanged

Fired when operation has changed. Handler gets a parameter with the new limit.

Type
string

operationColumnChanged

Fired when operationColumn has changed. Handler gets a parameter with the new operationColumn.

Type
string

Methods

getData ( )

Return the resulting data.

Returns
carto.dataview.CategoryData

getLimit ( )

Return the current categories limit.

Returns

Current dataview limit

number

getOperation ( )

Return the current dataview operation.

Returns

Current dataview operation

carto.operation

getOperationColumn ( )

Return the current dataview operationColumn.

Returns

Current dataview operationColumn

string

setLimit ( limit )

Set the categories limit.

Parameters
Name Description
limit number

Returns

this

carto.dataview.Category

setOperation ( operation )

Set the dataview operation.

Parameters
Name Description
operation carto.operation

Returns

this

carto.dataview.Category

setOperationColumn ( operationColumn )

Set the dataview operationColumn.

Parameters
Name Description
operationColumn string

Returns

this

carto.dataview.Category

carto.dataview.CategoryData

Type
object
Properties
Name
Description
count number

The total number of categories

max number

Maximum category value

min number

Minimum category value

nulls number

Number of null categories

operation string

Operation used

categories Array carto.dataview.CategoryItem

carto.dataview.CategoryItem

Type
object
Properties
Name
Description
group boolean

Category is a group

name string

Category name

value number

Category value

carto.dataview.Formula

A formula is a simple numeric operation applied to the column of a data source (dataset or sql query).

Like all dataviews, it is an async object so you must wait for the data to be available.

Options
Name Description
source carto.source.Base

The source where the dataview will fetch the data from

column string

The operation will be performed using this column

options

(Optional)

Name Description
options.operation

The operation to apply to the data

carto.operation

(Optional)

Extends

carto.dataview.Base
Example
1
2
3
4
5
	// Given a cities dataset get the most populated city
var formulaDataview = new carto.dataview.Formula(citiesSource, 'population', {
 operation: carto.operation.MAX,
});
	
CLICK TO COPY
Example
1
2
3
4
5
6
7
8
9
10
	// You can listen to multiple events emitted by a formula dataview.
// Data and status are fired by all dataviews.
formulaDataview.on('dataChanged', newData => { });
formulaDataview.on('statusChanged', (newData, error) => { });
formulaDataview.on('error', cartoError => { });

// Listen to specific formula-dataview events
formulaDataview.on('columnChanged', newData => { });
formulaDataview.on('operationChanged', newData => { });
	
CLICK TO COPY

Events

dataChanged

Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.

Type
carto.dataview.CategoryData
carto.dataview.FormulaData
carto.dataview.HistogramData
carto.dataview.TimeSeriesData

columnChanged

Fired when the column name has changed. Handler gets a parameter with the new column name.

Type
string

statusChanged

Fired when the status has changed. Handler gets a parameter with the new status.

Contains a single argument with the new status.

Type
carto.dataview.status

error

Fired when something went wrong on the server side.

Type
CartoError

operationChanged

Fired when operation has changed. Handler gets a parameter with the new limit.

Type
string

Methods

getData ( )

Return the resulting data.

Returns
carto.dataview.FormulaData

getOperation ( )

Return the current dataview operation.

Returns

Current dataview operation

carto.operation

setOperation ( operation )

Set the dataview operation.

Parameters
Name Description
operation carto.operation

Returns

this

carto.dataview.Formula

carto.dataview.FormulaData

Object containing formula data

Type
object
Properties
Name
Description
nulls number

Number of null values in the column

operation string

Operation used

result number

Result of the operation

carto.dataview.Histogram

A histogram is used to represent the distribution of numerical data.

See https://en.wikipedia.org/wiki/Histogram .

Options
Name Description
source carto.source.Base

The source where the dataview will fetch the data

column string

The column name to get the data

options

(Optional)

Name Description
options.bins number

Number of bins to aggregate the data range into

Default: 10

Extends

carto.dataview.Base
Example
1
2
3
4
5
6
7
	// Create a cities population histogram.
var histogram = new carto.dataview.Histogram(citiesSource, 'population');
// Set up a callback to render the histogram data every time new data is obtained.
 histogram.on('dataChanged', renderData);
// Add the histogram to the client
client.addDataview(histogram);
	
CLICK TO COPY
Example
1
2
3
4
5
6
7
8
9
10
11
	// Create a cities population histogram with only 4 bins
var histogram = new carto.dataview.Histogram(citiesSource, 'population', {bins: 4});
// Add a bounding box filter, so the data will change when the map is moved.
var bboxFilter = new carto.filter.BoundingBoxLeaflet(map);
// Set up a callback to render the histogram data every time new data is obtained.
 histogram.on('dataChanged', histogramData => {
   console.log(histogramData);
 });
// Add the histogram to the client
client.addDataview(histogram);
	
CLICK TO COPY
Example
1
2
3
4
5
6
	// The histogram is an async object so it can be on different states: LOADING, ERROR...
// Listen to state events
histogram.on('statusChanged', (newStatus, error) => { });
// Listen to histogram errors
histogram.on('error', error => { });
	
CLICK TO COPY

Events

dataChanged

Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.

Type
carto.dataview.CategoryData
carto.dataview.FormulaData
carto.dataview.HistogramData
carto.dataview.TimeSeriesData

columnChanged

Fired when the column name has changed. Handler gets a parameter with the new column name.

Type
string

statusChanged

Fired when the status has changed. Handler gets a parameter with the new status.

Contains a single argument with the new status.

Type
carto.dataview.status

error

Fired when something went wrong on the server side.

Type
CartoError

binsChanged

Fired when bins have changed. Handler gets a parameter with the new bins.

Type
number

Methods

getBins ( )

Return the current number of bins.

Returns

Current number of bins

number

getData ( )

Return the resulting data.

Returns
carto.dataview.HistogramData

getDistributionType ( )

Return the distribution type of the current data according to https://en.wikipedia.org/wiki/Multimodal_distribution#Galtung.27s_classification

Returns

Distribution type of current data

string

setBins ( bins )

Set the number of bins.

Parameters
Name Description
bins number

Returns

this

carto.dataview.Histogram

carto.dataview.HistogramData

Object containing histogram data.

Type
object
Properties
Name
Description
nulls number

The number of items with null value

totalAmount number

The number of elements returned

bins Array carto.dataview.BinItem

Array containing the data bins for the histogram

type string

String with value: histogram

carto.dataview.status

Enum for dataview status values.

Type
string
Properties
Name
Description
NOT_LOADED string

Not fetched with the server

LOADING string

Fetching with the server

LOADED string

Fetch completed

ERROR string

Error in fetch

carto.dataview.timeAggregation

Enum for dataview time aggregations.

Type
string
Properties
Name
Description
AUTO string

Auto

YEAR string

Year

QUARTER string

Quarter

MONTH string

Month

WEEK string

Week

DAY string

Day

HOUR string

Hour

MINUTE string

Minute

carto.dataview.TimeSeries

A dataview to represent an histogram of temporal data allowing to specify the granularity of the temporal bins.

Options
Name Description
source carto.source.Base

The source where the dataview will fetch the data

column string

The column name to get the data

options

(Optional)

Name Description
options.aggregation carto.dataview.timeAggregation

Granularity of time aggregation

Default: auto

options.offset

Number of hours to offset the aggregation from UTC

number

(Optional)

options.useLocalTimezone

Indicates whether to use the local user timezone, or not

boolean

(Optional)

Extends

carto.dataview.Base
Example
1
2
3
4
5
6
	// We have a tweets dataset and we want to show a "per hour histogram" with the data.
var timeSeries = new carto.dataview.TimeSeries(source0, 'last_review', {
 offset: 0,
 aggregation: 'hour'
});
	
CLICK TO COPY
Example
1
2
3
4
5
6
	// You can listen to multiple events emmited by the time-series-dataview.
// Data and status are fired by all dataviews.
timeSeries.on('dataChanged', newData => { });
timeSeries.on('statusChanged', (newData, error) => { });
timeSeries.on('error', cartoError => { });
	
CLICK TO COPY

Events

dataChanged

Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.

Type
carto.dataview.CategoryData
carto.dataview.FormulaData
carto.dataview.HistogramData
carto.dataview.TimeSeriesData

columnChanged

Fired when the column name has changed. Handler gets a parameter with the new column name.

Type
string

statusChanged

Fired when the status has changed. Handler gets a parameter with the new status.

Contains a single argument with the new status.

Type
carto.dataview.status

error

Fired when something went wrong on the server side.

Type
CartoError

binsChanged

Fired when bins have changed. Handler gets a parameter with the new bins.

Type
number

aggregationChanged

Fired when aggregation has changed. Handler gets a parameter with the new aggregation.

Type
string

offsetChanged

Fired when offset has changed. Handler gets a parameter with the new offset.

Type
string

localTimezoneChanged

Fired when localTimezone has changed. Handler gets a parameter with the new timezone.

Type
boolean

Methods

getAggregation ( )

Return the current time aggregation.

Returns

Current time aggregation

carto.dataview.timeAggregation

getData ( )

Return the resulting data.

Returns
carto.dataview.TimeSeriesData

getOffset ( )

Return the current time offset in hours.

Returns

Current time offset

number

isUsingLocalTimezone ( )

Return the current local timezone flag.

Returns

Current local timezone flag

boolean

setAggregation ( aggregation )

Set time aggregation.

Parameters
Name Description
aggregation carto.dataview.timeAggregation

Returns

this

carto.dataview.TimeSeries

setOffset ( offset )

Set time offset in hours.

Parameters
Name Description
offset number

Returns

this

carto.dataview.TimeSeries

useLocalTimezone ( enable , localTimezone )

Set the local timezone flag. If enabled, the time offset is overriden by the user's local timezone.

Parameters
Name Description
enable

localTimezone boolean

Returns

this

carto.dataview.TimeSeries

carto.dataview.TimeSeriesBinItem

Type
object
Properties
Name
Description
index number

Number indicating the bin order

start number

Starting UTC timestamp of the bin

end number

End UTC timestamp of the bin

min number

Minimum UTC timestamp present in the bin. Only appears if freq > 0

max number

Maximum UTC timestamp present in the bin. Only appears if freq > 0

freq number

Numbers of elements present in the bin

normalized number

Normalized frequency with respect to the whole dataset

carto.dataview.TimeSeriesData

Object containing time series data.

Type
object
Properties
Name
Description
nulls number

The number of items with null value

totalAmount number

The number of elements returned

offset number

The time offset in hours. Needed to format UTC timestamps into the proper timezone format

bins Array carto.dataview.TimeSeriesBinItem

Array containing the data bins for the time series

carto.filter.Base

Base filter object

carto.filter.BoundingBox

Generic bounding box filter.

When this filter is included into a dataview only the data inside a custom bounding box will be taken into account.

You can manually set the bounds via the .setBounds() method.

This filter could be useful if you want give the users to ability to select a portion of the map and update the dataviews accordingly.

Extends

carto.filter.Base

Events

boundsChanged

Fired when bounds have changed. Handler gets a parameter with the new bounds.

Type
carto.filter.Bounds

boundsChanged

Fired when bounds have changed. Handler gets a parameter with the new bounds.

Type
carto.filter.Bounds

Methods

getBounds ( )

Return the current bounds.

Returns

Current bounds

carto.filter.Bounds

resetBounds ( )

Reset the bounds.

Returns

this

carto.filter.BoundingBox

setBounds ( bounds )

Set the bounds.

Parameters
Name Description
bounds carto.filter.Bounds

Returns

this

carto.filter.BoundingBox

carto.filter.BoundingBoxGoogleMaps

Bounding box filter for Google Maps maps.

When this filter is included into a dataview only the data inside the googleMap bounds will be taken into account.

Options
Name Description
map google.maps.map

The google map to track the bounds

Extends

carto.filter.Base
Example
1
2
3
4
5
	// Create a bonding box attached to a google map.
const bboxFilter = new carto.filter.BoundingBoxGoogleMaps(googleMap);
// Add the filter to a dataview. Generating new data when the map bounds are changed.
dataview.addFilter(bboxFilter);
	
CLICK TO COPY

Events

boundsChanged

Fired when bounds have changed. Handler gets a parameter with the new bounds.

Type
carto.filter.Bounds

Methods

getBounds ( )

Return the current bounds.

Returns

Current bounds

carto.filter.Bounds

carto.filter.BoundingBoxLeaflet

Bounding box filter for Leaflet maps.

When this filter is included into a dataview only the data inside the leafletMap bounds will be taken into account.

Options
Name Description
map L.Map

The leaflet map view

Extends

carto.filter.Base
Example
1
2
3
4
5
	// Create a bonding box attached to a leaflet map.
const bboxFilter = new carto.filter.BoundingBoxLeaflet(leafletMap);
// Add the filter to a dataview. Generating new data when the map bounds are changed.
dataview.addFilter(bboxFilter);
	
CLICK TO COPY

Events

boundsChanged

Fired when bounds have changed. Handler gets a parameter with the new bounds.

Type
carto.filter.Bounds

Methods

getBounds ( )

Return the current bounds.

Returns

Current bounds

carto.filter.Bounds

carto.filter.Bounds

Type
object
Properties
Name
Description
west number

West coordinate

south number

South coordinate

east number

East coordinate

north number

North coordinate

carto.layer.Aggregation

An aggregation can be passed to a carto.layer.Layer to reduce the number of visible points increasing the performance.

See https://carto.com/docs/carto-engine/maps-api/tile-aggregation for more info.

Options
Name Description
opts
Name Description
opts.threshold number

The minimum number of rows in the dataset for aggregation to be applied

opts.resolution number

The cell-size of the spatial aggregation grid

opts.placement string

The kind of

opts.columns object

The new columns are computed by a applying an aggregate function to all the points in each group

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
	// Create a layer with aggregated data.
const aggregationOptions = {
  // CARTO applies aggregation if your dataset has more than threshold rows. In this case, more than 1 row.
  threshold: 1,
  // Defines the cell-size of the aggregation grid. In this case, 1x1 pixel. 
  resolution: 1,
  // Where the new point will be placed. In this case, at the center of the grid.
  placement: carto.layer.Aggregation.placement.GRID,
  // Here we define the aggregated columns that we want to obtain.
  columns: {
    // Each property key is the name of the new generated column
    avg_population: {
      // The aggregated column will contain the average of the original data.
      aggregateFunction: carto.layer.Aggregation.operation.AVG,
      // The column to be aggregated
      aggregatedColumn: 'population'
    }, {
    min_population: {
      aggregateFunction: carto.layer.Aggregation.operation.MIN,
      aggregatedColumn: 'population'
  }
};
const aggregation = new Aggregation(options);
const layer = new carto.layer.Layer(source, style, { aggregation: aggregation });
	
CLICK TO COPY

carto.layer.Base

Base layer object.

This object should not be used directly! use carto.layer.Layer instead.

Options
Name Description
source

layer

options

Events

error

Fired when something went wrong on the server side.

Type
CartoError

carto.layer.FeatureEvent

Event object for feature events triggered by carto.layer.Layer .

Type
object
Properties
Name
Description
latLng LatLng

Object with coordinates where interaction took place

data object

Object with feature data (one attribute for each specified column)

carto.layer.Layer

Represents a layer Object.

A layer is the primary way to visualize geospatial data.

To create a layer a source and styles are required:

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

  • The style is used to know how to draw the data in the Layer.

A layer alone won't do too much. In order to get data from the CARTO server you must add the Layer to a client .

				// Create a layer. Remember this won't do anything unless the layer is added to a client.
const layer = new carto.layer.Layer(source, style);
		
Options
Name Description
source carto.source.Base

The source where the layer will fetch the data

style carto.style.CartoCSS

A CartoCSS object with the layer styling

options

(Optional)

Name Description
options.featureClickColumns

Default: []

options.featureOverColumns

Default: []

options.aggregation carto.layer.Aggregation

Specify

Default: {}

options.id

An unique identifier for the layer

string

(Optional)

Extends

carto.layer.Base
Example
1
2
3
	// Create a layer with no options
new carto.layer.Layer(citiesSource, citiesStyle);
	
CLICK TO COPY
Example
1
2
3
4
5
6
7
8
9
10
11
12
	const citiesSource = new carto.source.SQL('SELECT * FROM cities');
const citiesStyle = new carto.style.CartoCSS(`
  #layer {
    marker-fill: #FABADA;
    marker-width: 10;
  }
`);
// Create a layer indicating what columns will be included in the featureOver event.
new carto.layer.Layer(citiesSource, citiesStyle, {
  featureOverColumns: [ 'name' ]
});
	
CLICK TO COPY
Example
1
2
3
4
5
	// Listen to the event thrown when the mouse is over a feature
layer.on('featureOver', featureEvent => {
  console.log(`Mouse over city with name: ${featureEvent.data.name}`);
});
	
CLICK TO COPY

Events

metadataChanged

Fired when style metadata has changed.

Type
carto.layer.MetadataEvent

featureClicked

Fired when user clicks on a feature.

Type
carto.layer.FeatureEvent

featureOut

Fired when user moves the mouse out of a feature.

Type
carto.layer.FeatureEvent

featureOver

Fired when user moves the mouse over a feature.

Type
carto.layer.FeatureEvent

error

Fired when something went wrong on the server side.

Type
CartoError

Methods

bringToBack ( )

Move the layer to the back.

Returns
Promise

bringToFront ( )

Move the layer to the front.

Returns
Promise

getFeatureClickColumns ( )

Get the columns available in featureClicked events.

Returns

Column names available in featureClicked events

Array string

getFeatureOverColumns ( )

Get the columns available in featureOver events.

Returns

Column names available in featureOver events

Array string

getSource ( )

Get the current source for this layer.

Returns

Current source

carto.source.Base

getStyle ( )

Get the current style for this layer.

Returns

Current style

carto.style.CartoCSS

hide ( )

Hides the layer.

Returns

this

carto.layer.Layer

isHidden ( )

Return true if the layer is not visible and false when visible.

Returns

A boolean value indicating the layer's visibility

boolean

isInteractive ( )

Return true if the layer has interactivity.

Returns

A boolean value indicating the layer's interactivity

boolean

isVisible ( )

Return true if the layer is visible and false when not visible.

Returns

A boolean value indicating the layer's visibility

boolean

setFeatureClickColumns ( columns )

Set new columns for featureClick events.

Parameters
Name Description
columns Array string

An array containing column names

Returns
Promise

setFeatureOverColumns ( columns )

Set new columns for featureOver events.

Parameters
Name Description
columns Array string

An array containing column names

Returns
Promise

setOrder ( index )

Set the layer's order.

Parameters
Name Description
index number

new order index for the layer.

Returns
Promise

show ( )

Shows the layer.

Returns

this

carto.layer.Layer

carto.layer.metadata.Base

Base metadata object

Options
Name Description
type

rule

Methods

getColumn ( )

Return the column of the metadata

Returns
string

getMapping ( )

Return the property of the metadata

Returns
string

getProperty ( )

Return the property of the metadata

Returns
string

getType ( )

Return the type of the metadata

Returns
string

carto.layer.metadata.Bucket

Type
object
Properties
Name
Description
min number

The minimum range value

max number

The maximum range value

value number|string

The value of the bucket

carto.layer.metadata.Buckets

Metadata type buckets

Adding a Turbocarto ramp (with ranges) in the style generates a response from the server with the resulting information, after computing the ramp. This information is wrapped in a metadata object of type 'buckets', that contains a list of buckets with the range (min, max) and the value. And also the total min, max range and the average of the total values.

For example, the following ramp will generate a metadata of type 'buckets' with numeric values (the size) in its buckets:

marker-width: ramp( , range(5, 20), quantiles(5));

In another example, this ramp will generate a metadata of type 'buckets' with string values (the color) in its buckets:

marker-fill: ramp( , (#FFC6C4, #EE919B, #CC607D), quantiles);

Options
Name Description
rule object

Rule with the cartocss metadata

Extends

carto.layer.metadata.Base

Methods

getAverage ( )

Return the average of the column

Returns
number

getBuckets ( )

Return the buckets

Returns
Array carto.layer.metadata.Bucket

getMax ( )

Return the maximum value in the ranges

Returns
number

getMin ( )

Return the minimum value in the ranges

Returns
number

carto.layer.metadata.Categories

Metadata type categories

Adding a Turbocarto ramp (with categories) in the style generates a response from the server with the resulting information after computing the ramp. This information is wrapped in a metadata object of type 'categories', that contains a list of categories with the name of the category and the value. And also the default value if it has been defined in the ramp.

For example, the following ramp will generate a metadata of type 'categories' with string values (the color) in its categories. The #CCCCCC is the default value in this case:

marker-fill: ramp( , (#F54690, #D16996, #CCCCCC), (1, 2), "=", category);

Options
Name Description
rule object

Rule with the cartocss metadata

Extends

carto.layer.metadata.Base

Methods

getCategories ( )

Return the buckets

Returns
Array carto.layer.metadata.Category

getDefaultValue ( )

Return the default value

Returns
string

carto.layer.metadata.Category

Type
object
Properties
Name
Description
name number|string

The name of the category

value string

The value of the category

carto.layer.MetadataEvent

Event fired by carto.layer.Layer when the style contains any TurboCarto ramp.

Type
object
Properties
Name
Description
styles Array carto.layer.metadata.Base

List of style metadata objects

carto.operation

Enum for operation values.

Type
string
Properties
Name
Description
COUNT string

Number of elements

SUM string

Sum

AVG string

Average

MAX string

Maximum

MIN string

Minimum

carto.source.Base

Base data source object.

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

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

carto.source.Base should not be used directly use carto.source.Dataset or carto.source.SQL instead.

Events

error

Fired when something went wrong on the server side.

Type
CartoError

carto.source.Dataset

A Dataset that can be used as the data source for layers and dataviews.

Options
Name Description
tableName string

The name of an existing table

Extends

carto.source.Base
Example
1
2
	new carto.source.Dataset('european_cities');
	
CLICK TO COPY

Events

error

Fired when something went wrong on the server side.

Type
CartoError

Methods

getTableName ( )

Return the table name being used in this Dataset object.

Returns

The table name being used in this Dataset object

string

carto.source.SQL

A SQL Query that can be used as the data source for layers and dataviews.

Options
Name Description
query string

A SQL query containing a SELECT statement

Extends

carto.source.Base
Example
1
2
	new carto.source.SQL('SELECT * FROM european_cities');
	
CLICK TO COPY

Events

error

Fired when something went wrong on the server side.

Type
CartoError

queryChanged

Fired when the query has changed. Handler gets a parameter with the new query.

Type
string

Methods

getQuery ( )

Get the query being used in this SQL source.

Returns

The query being used in this SQL object

string

setQuery ( query )

Update the query. This method is asyncronous and returns a promise which is resolved when the style is changed succesfully. It also fires a 'queryChanged' event.

Parameters
Name Description
query string

The sql query that will be the source of the data

Returns

A promise that will be fulfilled when the reload cycle is completed

Promise

carto.style.Base

Base style object.

Events

error

Fired when something went wrong on the server side.

Type
CartoError

carto.style.CartoCSS

A CartoCSS/TurboCarto style that can be applied to a carto.layer.Layer .

Options
Name Description
content string

A CartoCSS string

Extends

carto.style.Base
Example
1
2
3
4
5
6
7
	var style = new carto.style.CartoCSS(`
  #layer {
    marker-fill: #FABADA;
    marker-width: 10;
  }
`);
	
CLICK TO COPY

Methods

getContent ( )

Get the current CartoCSS/TurboCarto style as a string.

Returns

The TurboCarto style for this CartoCSS object

string

setContent ( newContent )

Set the CartoCSS/Turbocarto as a string.

Parameters
Name Description
newContent string

A string containing the new cartocss/turbocarto style

Returns

A promise that will be resolved once the cartocss/turbocarto is updated

Promise string
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
	// Get the cartoCSS from an exiting layer
let cartoCSS = layer.getStyle();
// Update the cartoCSS content, remember this method is asynchronous!
cartoCSS.setContent(`
 #layer {
   marker-fill: blue;
 }`)
 .then(() => {
   console.log('cartoCSS was updated'); 
 })
 .catch(() => {
   console.error('Error updating the cartoCSS for the layer');
 });
	
CLICK TO COPY

CartoError

Represents an error in the carto library.

Some actions like adding a layer to a map are asynchronous and require a server round trip. If some error happens during this communnication with the server, an error with a CartoError object will be fired.

CartoErrors can be obtained by listening to the client 'error' client.on('error', callback); , through any async action or by listening to 'error' events on particular objects (eg: dataviews).

Promises are also rejected with a CartoError.

Type
object
Properties
Name
Description
message string

A short error description

name string

The name of the error "CartoError"

origin string

Where the error was originated: 'windshaft' | 'ajax' | 'validation'

originalError object

An object containing the internal/original error

stack object

Error stack trace

type string

Error type

Example
1
2
3
4
5
	// Listen when a layer has been added or there has been an error.
client.addLayer(layerWithErrors)
 .then(()=> console.log('Layer added succesfully'))
 .catch(cartoError => console.error(cartoError.message))
	
CLICK TO COPY
Example
1
2
3
4
5
6
7
8
9
	// Events also will be registered here when the map changes.
client.on('success', function () {
 console.log('Client reloaded');
});

client.on('error', function (clientError) {
 console.error(clientError.message);
});
	
CLICK TO COPY
Example
1
2
3
4
5
	// Listen when there is an error in a dataview
dataview.on('error', function (error) {
  console.error(error.message);
});
	
CLICK TO COPY

LatLng

Type
object
Properties
Name
Description
lat number

Latitude

lng number

Longitude