CARTO.js

Integrate interactive maps and location data into your web applications and websites.

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

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 v4, 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 v4 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://libs.cartocdn.com/carto.js/v4.2.0/carto.min.js"></script>

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

var carto = require('@carto/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

Type
constant

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.

Type
class
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 string

URL of the windshaft server. Only needed in custom installations. Pattern: http(s)://{username}.your.carto.instance or http(s)://your.carto.instance/user/{username} (only for On-Premises environments).

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

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: 'http://{username}.your.carto.instance'
});
		
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 carto.dataview.Base Array

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 carto.layer.Base Array

An array with the layers to be added. Note that ([A, B]) displays B as the top layer.

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

carto.dataview.Base Array
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

carto.layer.Base Array
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 ( options )

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

Parameters
Name Description
options object

L.TileLayer options.

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 carto.layer.Base Array

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.

Type
class
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 available.

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

Type
class
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 carto.dataview.CategoryItem Array

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.

Type
class
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 .

Type
class
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

options.start

Lower limit of the data range, if not present, the lower limit of the actual data will be used. Start and end values must be used together.

number

(Optional)

options.end

Upper limit of the data range, if not present, the upper limit of the actual data will be used. Start and end values must be used together.

number

(Optional)

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
7
8
9
		// Create a cities population histogram with a range
var histogram = new carto.dataview.Histogram(citiesSource, 'population', { start: 100000, end: 5000000 });
// 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 [Galtung’s AJUS System]{@link https://en.wikipedia.org/wiki/Multimodal_distribution#Galtung.27s_classification}

Returns

Distribution type of current data

string

getEnd

Return the upper limit of the bins' range

Returns

Current value of end

number

getStart

Return the lower limit of the bins' range

Returns

Current value of start

number

setBins ( bins )

Set the number of bins.

Parameters
Name Description
bins number
Returns

this

carto.dataview.Histogram

setStartEnd ( start , end )

Set the lower and upper limit of the bins range

Parameters
Name Description
start number
end 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 carto.dataview.BinItem Array

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

MILLENNIUM string

Millennium

CENTURY string

Century

DECADE string

Decade

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.

Type
class
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 carto.dataview.TimeSeriesBinItem Array

Array containing the data bins for the time series

carto.filter.AND

When including this filter into a carto.source.SQL or a carto.source.Dataset , the rows will be filtered by the conditions included within filters.

This filter will group as many filters as you want and it will add them to the query returning the rows that match ALL the filters to render the visualization.

You can add or remove filters by invoking .addFilter() and .removeFilter() .

Type
class

Extends

carto.filter.FiltersCollection
Example
1
2
3
4
5
6
7
8
9
10
11
		// Create a filter by room type, showing only private rooms
const roomTypeFilter = new carto.filter.Category('room_type', { eq: 'Private room' });
// Create a filter by price, showing only listings lower than or equal to 50€
const priceFilter = new carto.filter.Range('price', { lte: 50 });

// Combine the filters with an AND condition, returning rows that match both filters
const filterByRoomTypeAndPrice = new carto.filter.AND([ roomTypeFilter, priceFilter ]);

// Add filters to the existing source
source.addFilter(filterByRoomTypeAndPrice);
		
CLICK TO COPY

carto.filter.Base

Base filter object

Type
class

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.

Type
class

Extends

carto.filter.Base

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

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.

Type
class
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.

Type
class
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.filter.Category

When including this filter into a carto.source.SQL or a carto.source.Dataset , the rows will be filtered by the conditions included within the filter.

You can filter columns with in , notIn , eq , notEq , like , similarTo filters, and update the conditions with .set() or .setFilters() method. It will refresh the visualization automatically when any filter is added or modified.

This filter won't include null values within returned rows by default but you can include them by setting includeNull option.

Type
class
Options
Name Description
column string

The column which the filter will be performed against

filters
Name Description
filters.in string Array | object

Return rows whose column value is included within the provided values

Name Description
filters.in.query string

Return rows whose column value is included within query results

filters.notIn string Array | object

Return rows whose column value is included within the provided values

Name Description
filters.notIn.query string

Return rows whose column value is not included within query results

filters.eq string | number | Date | object

Return rows whose column value is equal to the provided value

Name Description
filters.eq.query string

Return rows whose column value is equal to the value returned by query

filters.notEq string | number | Date | object

Return rows whose column value is not equal to the provided value

Name Description
filters.notEq.query string

Return rows whose column value is not equal to the value returned by query

filters.like string

Return rows whose column value is like the provided value

filters.similarTo string

Return rows whose column value is similar to the provided values

options

(Optional)

Name Description
options.includeNull

Include null rows when returning data

boolean

(Optional)

Extends

carto.filter.Base
Example
1
2
3
4
		// Create a filter by room type, showing only private rooms
const roomTypeFilter = new carto.filter.Category('room_type', { eq: 'Private Room' });
airbnbDataset.addFilter(roomTypeFilter);
		
CLICK TO COPY
Example
1
2
3
4
		// Create a filter by room type, showing only private rooms and entire apartments
const roomTypeFilter = new carto.filter.Category('room_type', { in: ['Private Room', 'Entire home/apt'] });
airbnbDataset.addFilter(roomTypeFilter);
		
CLICK TO COPY
Example
1
2
3
4
		// Create a filter by room type, showing results included in subquery
const roomTypeFilter = new carto.filter.Category('room_type', { in: { query: 'SELECT distinct(type) FROM rooms' } });
airbnbDataset.addFilter(roomTypeFilter);
		
CLICK TO COPY

Methods

resetFilters

Remove all conditions from current filter

set ( filterType , filterValue )

Set any of the filter conditions, overwriting the previous one.

Parameters
Name Description
filterType string

The filter type that you want to set. in , notIn , eq , notEq , like , similarTo .

filterValue string

The value of the filter. Check types in carto.filter.Category

setFilters ( filters )

Set filter conditions, overriding all the previous ones.

Parameters
Name Description
filters object

Object containing all the new filters to apply. Check filter options in carto.filter.Category .

carto.filter.Circle

Generic circle filter.

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

You can manually set the circle properties with the setCircle() .

This filter could be useful if you want give the users the ability to select a buffer around a point of interest in the map and update the dataviews accordingly.

Type
class

Extends

carto.filter.Base

Events

circleChanged

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

Type
carto.filter.CircleData

Methods

getCircle

Return the current circle data

Returns

Current circle data

carto.filter.CircleData

resetCircle

Reset the circle.

Returns

this

carto.filter.Circle

setCircle ( circle )

Set the circle.

Parameters
Name Description
circle carto.filter.CircleData
Returns

this

carto.filter.Circle

carto.filter.CircleData

Type
object
Properties
Name
Description
lat number

Center Latitude WGS84

lng number

Center Longitude WGS84

radius number

Radius in meters

carto.filter.FiltersCollection

Base class for AND and OR filters.

Filters Collection is a way to group a set of filters in order to create composed filters, allowing the user to change the operator that joins the filters.

This object should not be used directly.

Type
class

Extends

carto.filter.Base

Methods

addFilter ( filter )

Add a new filter to collection

Parameters

count

Get the number of added filters

Returns

Number of contained filters

number

getFilters

Get added filters

Returns

Added filters

Array

removeFilter ( filter )

Remove an existing filter from collection

Parameters
Returns

The removed element

carto.filter.Range | carto.filter.Category | carto.filter.AND | carto.filter.OR

carto.filter.OR

When including this filter into a carto.source.SQL or a carto.source.Dataset , the rows will be filtered by the conditions included within filters.

This filter will group as many filters as you want and it will add them to the query returning the rows that match ANY of the filters to render the visualization.

You can add or remove filters by invoking .addFilter() and .removeFilter() .

Type
class

Extends

carto.filter.FiltersCollection
Example
1
2
3
4
5
6
7
8
9
10
11
		// Create a filter by room type, showing only private rooms
const roomTypeFilter = new carto.filter.Category('room_type', { eq: 'Private room' });
// Create a filter by price, showing only listings lower than or equal to 50€
const priceFilter = new carto.filter.Range('price', { lte: 50 });

// Combine the filters with an OR operator, returning rows that match one or the other filter
const filterByRoomTypeOrPrice = new carto.filter.OR([ roomTypeFilter, priceFilter ]);

// Add filters to the existing source
source.addFilter(filterByRoomTypeOrPrice);
		
CLICK TO COPY

carto.filter.Polygon

Generic polygon filter.

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

You can manually set the polygon with the setPolygon() .

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

Type
class

Extends

carto.filter.Base

Events

polygonChanged

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

Type
carto.filter.PolygonData

Methods

getPolygon

Return the current polygon data

Returns

Current polygon data, expressed as a GeoJSON geometry fragment

carto.filter.PolygonData

resetPolygon

Reset the polygon.

Returns

this

carto.filter.Polygon

setPolygon ( polygon )

Set the polygon.

Parameters
Name Description
polygon carto.filter.PolygonData
Returns

this

carto.filter.Polygon

carto.filter.PolygonData

Type
object
Properties
Name
Description
type string

Geometry type, Just 'Polygon' is valid

coordinates Array

Array of coordinates [lng, lat] as defined in GeoJSON geometries

carto.filter.Range

When including this filter into a carto.source.SQL or a carto.source.Dataset , the rows will be filtered by the conditions included within the filter.

You can filter columns with in , notIn , eq , notEq , like , similarTo filters, and update the conditions with .set() or .setFilters() method. It will refresh the visualization automatically when any filter is added or modified.

This filter won't include null values within returned rows by default but you can include them by setting includeNull option.

Type
class
Options
Name Description
column string

The column to filter rows

filters
Name Description
filters.lt number | Date | object

Return rows whose column value is less than the provided value

Name Description
filters.lt.query string

Return rows whose column value is less than the value returned by query

filters.lte number | Date | object

Return rows whose column value is less than or equal to the provided value

Name Description
filters.lte.query string

Return rows whose column value is less than or equal to the value returned by query

filters.gt number | Date | object

Return rows whose column value is greater than the provided value

Name Description
filters.gt.query string

Return rows whose column value is greater than the value returned by query

filters.gte number | Date | object

Return rows whose column value is greater than or equal to the provided value

Name Description
filters.gte.query string

Return rows whose column value is greater than or equal to the value returned by query

filters.between number | Date

Return rows whose column value is between the provided values

Name Description
filters.between.min number | Date

Lower value of the comparison range

filters.between.max number | Date

Upper value of the comparison range

filters.notBetween number | Date

Return rows whose column value is not between the provided values

Name Description
filters.notBetween.min number | Date

Lower value of the comparison range

filters.notBetween.max number | Date

Upper value of the comparison range

filters.betweenSymmetric number | Date

Return rows whose column value is between the provided values after sorting them

Name Description
filters.betweenSymmetric.min number | Date

Lower value of the comparison range

filters.betweenSymmetric.max number | Date

Upper value of the comparison range

filters.notBetweenSymmetric number | Date

Return rows whose column value is not between the provided values after sorting them

Name Description
filters.notBetweenSymmetric.min number | Date

Lower value of the comparison range

filters.notBetweenSymmetric.max number | Date

Upper value of the comparison range

options

(Optional)

Name Description
options.includeNull

Include null rows when returning data

boolean

(Optional)

Extends

carto.filter.Base
Example
1
2
3
4
5
6
		// Create a filter by price, showing only listings lower than or equal to 50€, and higher than 100€
const priceFilter = new carto.filter.Range('price', { lte: 50, gt: 100 });

// Add filter to the existing source
airbnbDataset.addFilter(priceFilter);
		
CLICK TO COPY
Example
1
2
3
4
5
6
		// Create a filter by price, showing only listings greater than or equal to the average price
const priceFilter = new carto.filter.Range('price', { gte: { query: 'SELECT avg(price) FROM listings' } });

// Add filter to the existing source
airbnbDataset.addFilter(priceFilter);
		
CLICK TO COPY

Methods

resetFilters

Remove all conditions from current filter

set ( filterType , filterValue )

Set any of the filter conditions, overwriting the previous one.

Parameters
Name Description
filterType string

The filter type that you want to set. lt , lte , gt , gte , between , notBetween , betweenSymmetric , notBetweenSymmetric .

filterValue string

The value of the filter. Check types in carto.filter.Range

setFilters ( filters )

Set filter conditions, overriding all the previous ones.

Parameters
Name Description
filters object

Object containing all the new filters to apply. Check filter options in carto.filter.Range .

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/developers/maps-api/guides/tile-aggregation/ for more info.

Type
class
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 [more info]{@link https://carto.com/developers/maps-api/tile-aggregation#resolution}

opts.placement string

The kind of [aggregated geometry]{@link https://carto.com/developers/maps-api/tile-aggregation#placement} generated

opts.columns object

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

Name Description
opts.columns.aggregatedFunction string

The Function used to aggregate the points: avg (average), sum, min (minimum), max (maximum) and mode (the most frequent value in the group)

opts.columns.aggregatedColumn string

The name of the original column to be aggregated.

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.

Type
class
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);
		
Type
class
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 string Array

Columns that will be available for featureClick events

Default: []

options.visible boolean

A boolean value indicating the layer's visibility

Default: true

options.featureOverColumns string Array

Columns that will be available for featureOver events

Default: []

options.aggregation carto.layer.Aggregation

Specify aggregation options

Default: {}

options.id

An unique identifier for the layer

string

(Optional)

Extends

carto.layer.Base
Example
1
2
3
4
5
6
7
8
9
10
		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 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
6
7
8
9
10
		const citiesSource = new carto.source.SQL('SELECT * FROM cities');
const citiesStyle = new carto.style.CartoCSS(`
  #layer {
    marker-fill: #FABADA;
    marker-width: 10;
  }
`);
// Create a hidden layer
new carto.layer.Layer(citiesSource, citiesStyle, { visible: false });
		
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

string Array

getFeatureOverColumns

Get the columns available in featureOver events.

Returns

Column names available in featureOver events

string Array

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 string Array

An array containing column names

Returns
Promise

setFeatureOverColumns ( columns )

Set new columns for featureOver events.

Parameters
Name Description
columns string Array

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

Type
class
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([scalerank], 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([scalerank], (#FFC6C4, #EE919B, #CC607D), quantiles);

Type
class
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
carto.layer.metadata.Bucket Array

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([scalerank], (#F54690, #D16996, #CCCCCC), (1, 2), "=", category);

Type
class
Options
Name Description
rule object

Rule with the cartocss metadata

Extends

carto.layer.metadata.Base

Methods

getCategories

Return the buckets

Returns
carto.layer.metadata.Category Array

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 carto.layer.metadata.Base Array

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.

Type
class

Events

error

Fired when something went wrong on the server side.

Type
CartoError

Methods

addFilter ( filter )

Add new filter to the source

Parameters

addFilters ( filters )

Add new filters to the source

Parameters
Name Description
filters Array

getFilters

Get added filters

Returns

Added filters

Array

removeFilter ( filter )

Remove an existing filter from source

Parameters

removeFilters ( filters )

Remove existing filters from source

Parameters
Name Description
filters Array

carto.source.Dataset

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

Type
class
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

setTableName ( tableName )

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

Parameters
Name Description
tableName string

The name of an existing table

Returns

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

Promise

carto.source.SQL

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

Type
class
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.

Type
class

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 .

Type
class
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

string Promise
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

sourceId string

Available if the error is related to a source object. Indicates the ID of the source that has a problem.

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