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

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'
});
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
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');
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);
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.
| Name | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| settings | 
 | 
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'
});
	
Add a dataview to the client.
| Name | Description | 
|---|---|
| dataview | carto.dataview.BaseThe dataview to be added | 
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);
 }):
	
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);
 }):
	
Add a layer to the client. If the layer id already exists in the client this method will throw an error.
| Name | Description | 
|---|---|
| layer | carto.layer.BaseThe layer to be added | 
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);
 });
	
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);
 });
	
Get all the dataviews from the client.
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();
	
Return a google.maps.MapType that groups all the layers that have been added to this client.
| Name | Description | 
|---|---|
| map | google.maps.MapThe native Google Maps map where the CARTO layers will be displayed. | 
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();
	
Example
1
2
3
	// Add googlemaps MapType to a google map
googleMap.overlayMapTypes.push(client.getGoogleMapsMapType(googleMap));
	
Get all the layers from the client.
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();
	
Example
1
2
3
	// Hide all layers from the client
client.getLayers().forEach(layer => layer.hide());
	
Return a leaflet layer that groups all the layers that have been added to this client.
A L.TileLayer layer that groups all the layers.
Example
1
2
3
	// Get the leafletlayer from the client
const cartoLeafletLayer = client.getLeafletLayer();
	
Example
1
2
3
	// Add the leafletLayer to a leafletMap
client.getLeafletLayer().addTo(map);
	
Move layer order.
| Name | Description | 
|---|---|
| layer | carto.layer.BaseThe layer to be moved | 
| toIndex | carto.layer.BaseThe layer to be moved | 
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);
});
	
Remove a dataview from the client.
| Name | Description | 
|---|---|
| dataview | carto.dataview.BaseThe dataview array to be removed | 
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);
 }):
	
Remove a layer from the client.
| Name | Description | 
|---|---|
| layer | carto.layer.BaseThe layer to be removed | 
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);
});
	
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);
});
	
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);
})
	
Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.
carto.dataview.CategoryData
        
    
                        
                            
	
        
        	carto.dataview.FormulaData
        
    
                        
                            
	
        
        	carto.dataview.HistogramData
        
    
                        
                            
	
        
        	carto.dataview.TimeSeriesData
        
    
                        
                    
                
                Fired when the column name has changed. Handler gets a parameter with the new column name.
string
                        
                    
                
                Fired when the status has changed. Handler gets a parameter with the new status.
Contains a single argument with the new status.
carto.dataview.status
                        
                    
                
                Add a filter .
| Name | Description | 
|---|---|
| filter | carto.filter.Base | 
this
carto.dataview.Base
        
    
                    
                    
                    
                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).
this
carto.dataview.Base
        
    
                    
                    
                    
                Enable the dataview. When enabled, a dataview fetches new data when the map changes (changing map configuration or changing map bounding box).
this
carto.dataview.Base
        
    
                    
                    
                    
                Return the current source where the dataview gets the data from.
Current source object
carto.source.Base
        
    
                    
                    
                    
                Check if a filter exists in the dataview.
| Name | Description | 
|---|---|
| filter | carto.filter.Base | 
this
carto.dataview.Base
        
    
                    
                    
                    
                Remove a filter .
| Name | Description | 
|---|---|
| filter | carto.filter.Base | 
this
carto.dataview.Base
        
    
                    
                    
                    
                object
        
        
        
| Name | Description | 
|---|---|
| index | numberNumber indicating the bin order | 
| start | numberThe lower limit of the bin | 
| end | numberThe higher limit of the bin | 
| min | numberThe minimal value appearing in the bin. Only appears if freq > 0 | 
| max | numberThe minimal value appearing in the bin. Only appears if freq > 0 | 
| avg | numberThe average value of the elements for this bin. Only appears if freq > 0 | 
| freq | numberNumber of elements in the bin | 
| normalized | numberNormalized 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
});
	
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
| Name | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| source | carto.source.BaseThe source where the dataview will fetch the data | ||||||||
| column | stringThe name of the column used to create categories | ||||||||
| options | (Optional) 
 | 
	    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.
 });
	
Example
1
2
3
4
5
	// Listen for data updates
categoryDataview.on('dataChanged', newData => {
 console.log(newData); // CategoryData object
});
	
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 => { });
	
Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.
carto.dataview.CategoryData
        
    
                        
                            
	
        
        	carto.dataview.FormulaData
        
    
                        
                            
	
        
        	carto.dataview.HistogramData
        
    
                        
                            
	
        
        	carto.dataview.TimeSeriesData
        
    
                        
                    
                
                Fired when the column name has changed. Handler gets a parameter with the new column name.
string
                        
                    
                
                Fired when the status has changed. Handler gets a parameter with the new status.
Contains a single argument with the new status.
carto.dataview.status
                        
                    
                
                Fired when operationColumn has changed. Handler gets a parameter with the new operationColumn.
string
                        
                    
                
                Set the categories limit.
| Name | Description | 
|---|---|
| limit | number | 
this
carto.dataview.Category
        
    
                    
                    
                    
                Set the dataview operation.
| Name | Description | 
|---|---|
| operation | carto.operation | 
this
carto.dataview.Category
        
    
                    
                    
                    
                Set the dataview operationColumn.
| Name | Description | 
|---|---|
| operationColumn | string | 
this
carto.dataview.Category
        
    
                    
                    
                    
                object
        
        
        
| Name | Description | 
|---|---|
| count | numberThe total number of categories | 
| max | numberMaximum category value | 
| min | numberMinimum category value | 
| nulls | numberNumber of null categories | 
| operation | stringOperation used | 
| categories | Arraycarto.dataview.CategoryItem | 
object
        
        
        
| Name | Description | 
|---|---|
| group | booleanCategory is a group | 
| name | stringCategory name | 
| value | numberCategory value | 
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.
| Name | Description | ||||
|---|---|---|---|---|---|
| source | carto.source.BaseThe source where the dataview will fetch the data from | ||||
| column | stringThe operation will be performed using this column | ||||
| options | (Optional) 
 | 
	    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,
});
	
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 => { });
	
Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.
carto.dataview.CategoryData
        
    
                        
                            
	
        
        	carto.dataview.FormulaData
        
    
                        
                            
	
        
        	carto.dataview.HistogramData
        
    
                        
                            
	
        
        	carto.dataview.TimeSeriesData
        
    
                        
                    
                
                Fired when the column name has changed. Handler gets a parameter with the new column name.
string
                        
                    
                
                Fired when the status has changed. Handler gets a parameter with the new status.
Contains a single argument with the new status.
carto.dataview.status
                        
                    
                
                Set the dataview operation.
| Name | Description | 
|---|---|
| operation | carto.operation | 
this
carto.dataview.Formula
        
    
                    
                    
                    
                Object containing formula data
object
        
        
        
| Name | Description | 
|---|---|
| nulls | numberNumber of null values in the column | 
| operation | stringOperation used | 
| result | numberResult of the operation | 
A histogram is used to represent the distribution of numerical data.
See https://en.wikipedia.org/wiki/Histogram .
| Name | Description | ||||
|---|---|---|---|---|---|
| source | carto.source.BaseThe source where the dataview will fetch the data | ||||
| column | stringThe column name to get the data | ||||
| options | (Optional) 
 | 
	    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);
	
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);
	
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 => { });
	
Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.
carto.dataview.CategoryData
        
    
                        
                            
	
        
        	carto.dataview.FormulaData
        
    
                        
                            
	
        
        	carto.dataview.HistogramData
        
    
                        
                            
	
        
        	carto.dataview.TimeSeriesData
        
    
                        
                    
                
                Fired when the column name has changed. Handler gets a parameter with the new column name.
string
                        
                    
                
                Fired when the status has changed. Handler gets a parameter with the new status.
Contains a single argument with the new status.
carto.dataview.status
                        
                    
                
                Return the distribution type of the current data according to https://en.wikipedia.org/wiki/Multimodal_distribution#Galtung.27s_classification
Distribution type of current data
string
	
                    
                    
                    
                Set the number of bins.
| Name | Description | 
|---|---|
| bins | number | 
this
carto.dataview.Histogram
        
    
                    
                    
                    
                Object containing histogram data.
object
        
        
        
| Name | Description | 
|---|---|
| nulls | numberThe number of items with null value | 
| totalAmount | numberThe number of elements returned | 
| bins | Arraycarto.dataview.BinItemArray containing the data bins for the histogram | 
| type | stringString with value: histogram | 
Enum for dataview status values.
string
            
            
            
                
| Name | Description | 
|---|---|
| NOT_LOADED | stringNot fetched with the server | 
| LOADING | stringFetching with the server | 
| LOADED | stringFetch completed | 
| ERROR | stringError in fetch | 
Enum for dataview time aggregations.
string
            
            
            
                
| Name | Description | 
|---|---|
| AUTO | stringAuto | 
| YEAR | stringYear | 
| QUARTER | stringQuarter | 
| MONTH | stringMonth | 
| WEEK | stringWeek | 
| DAY | stringDay | 
| HOUR | stringHour | 
| MINUTE | stringMinute | 
A dataview to represent an histogram of temporal data allowing to specify the granularity of the temporal bins.
| Name | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| source | carto.source.BaseThe source where the dataview will fetch the data | ||||||||
| column | stringThe column name to get the data | ||||||||
| options | (Optional) 
 | 
	    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'
});
	
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 => { });
	
Fired when the data has changed. Handler gets an object with specific data for the type of dataview that triggered the event.
carto.dataview.CategoryData
        
    
                        
                            
	
        
        	carto.dataview.FormulaData
        
    
                        
                            
	
        
        	carto.dataview.HistogramData
        
    
                        
                            
	
        
        	carto.dataview.TimeSeriesData
        
    
                        
                    
                
                Fired when the column name has changed. Handler gets a parameter with the new column name.
string
                        
                    
                
                Fired when the status has changed. Handler gets a parameter with the new status.
Contains a single argument with the new status.
carto.dataview.status
                        
                    
                
                Return the current time aggregation.
Current time aggregation
carto.dataview.timeAggregation
        
    
                    
                    
                    
                Set time aggregation.
| Name | Description | 
|---|---|
| aggregation | carto.dataview.timeAggregation | 
this
carto.dataview.TimeSeries
        
    
                    
                    
                    
                Set time offset in hours.
| Name | Description | 
|---|---|
| offset | number | 
this
carto.dataview.TimeSeries
        
    
                    
                    
                    
                Set the local timezone flag. If enabled, the time offset is overriden by the user's local timezone.
| Name | Description | 
|---|---|
| enable | |
| localTimezone | boolean | 
this
carto.dataview.TimeSeries
        
    
                    
                    
                    
                object
        
        
        
| Name | Description | 
|---|---|
| index | numberNumber indicating the bin order | 
| start | numberStarting UTC timestamp of the bin | 
| end | numberEnd UTC timestamp of the bin | 
| min | numberMinimum UTC timestamp present in the bin. Only appears if freq > 0 | 
| max | numberMaximum UTC timestamp present in the bin. Only appears if freq > 0 | 
| freq | numberNumbers of elements present in the bin | 
| normalized | numberNormalized frequency with respect to the whole dataset | 
Object containing time series data.
object
        
        
        
| Name | Description | 
|---|---|
| nulls | numberThe number of items with null value | 
| totalAmount | numberThe number of elements returned | 
| offset | numberThe time offset in hours. Needed to format UTC timestamps into the proper timezone format | 
| bins | Arraycarto.dataview.TimeSeriesBinItemArray containing the data bins for the time series | 
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.
	    carto.filter.Base
    
        Fired when bounds have changed. Handler gets a parameter with the new bounds.
carto.filter.Bounds
                        
                    
                
                Fired when bounds have changed. Handler gets a parameter with the new bounds.
carto.filter.Bounds
                        
                    
                
                Set the bounds.
| Name | Description | 
|---|---|
| bounds | carto.filter.Bounds | 
this
carto.filter.BoundingBox
        
    
                    
                    
                    
                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.
| Name | Description | 
|---|---|
| map | google.maps.mapThe google map to track the bounds | 
	    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);
	
Fired when bounds have changed. Handler gets a parameter with the new bounds.
carto.filter.Bounds
                        
                    
                
                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.
| Name | Description | 
|---|---|
| map | L.MapThe leaflet map view | 
	    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);
	
Fired when bounds have changed. Handler gets a parameter with the new bounds.
carto.filter.Bounds
                        
                    
                
                object
        
        
        
| Name | Description | 
|---|---|
| west | numberWest coordinate | 
| south | numberSouth coordinate | 
| east | numberEast coordinate | 
| north | numberNorth coordinate | 
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.
| Name | Description | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| opts | 
 | 
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 });
	
Base layer object.
This object should not be used directly! use carto.layer.Layer instead.
| Name | Description | 
|---|---|
| source | |
| layer | |
| options | 
Event object for feature events triggered by carto.layer.Layer .
object
        
        
        
| Name | Description | 
|---|---|
| latLng | LatLngObject with coordinates where interaction took place | 
| data | objectObject with feature data (one attribute for each specified column) | 
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);
		| Name | Description | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| source | carto.source.BaseThe source where the layer will fetch the data | ||||||||||
| style | carto.style.CartoCSSA CartoCSS object with the layer styling | ||||||||||
| options | (Optional) 
 | 
	    carto.layer.Base
    
        Example
1
2
3
	// Create a layer with no options
new carto.layer.Layer(citiesSource, citiesStyle);
	
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' ]
});
	
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}`);
});
	
Get the columns available in featureClicked events.
Column names available in featureClicked events
Array
string
                    
                    
                    
                Get the columns available in featureOver events.
Column names available in featureOver events
Array
string
                    
                    
                    
                Set new columns for featureClick events.
| Name | Description | 
|---|---|
| columns | ArraystringAn array containing column names | 
Promise
	
                    
                    
                    
                Set new columns for featureOver events.
| Name | Description | 
|---|---|
| columns | ArraystringAn array containing column names | 
Promise
	
                    
                    
                    
                object
        
        
        
| Name | Description | 
|---|---|
| min | numberThe minimum range value | 
| max | numberThe maximum range value | 
| value | number|string | 
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);
| Name | Description | 
|---|---|
| rule | objectRule with the cartocss metadata | 
	    carto.layer.metadata.Base
    
        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);
| Name | Description | 
|---|---|
| rule | objectRule with the cartocss metadata | 
	    carto.layer.metadata.Base
    
        object
        
        
        
| Name | Description | 
|---|---|
| name | number|string | 
| value | stringThe value of the category | 
Event fired by carto.layer.Layer when the style contains any TurboCarto ramp.
object
        
        
        
| Name | Description | 
|---|---|
| styles | Arraycarto.layer.metadata.BaseList of style metadata objects | 
Enum for operation values.
string
            
            
            
                
| Name | Description | 
|---|---|
| COUNT | stringNumber of elements | 
| SUM | stringSum | 
| AVG | stringAverage | 
| MAX | stringMaximum | 
| MIN | stringMinimum | 
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.
A Dataset that can be used as the data source for layers and dataviews.
| Name | Description | 
|---|---|
| tableName | stringThe name of an existing table | 
	    carto.source.Base
    
        Example
1
2
	new carto.source.Dataset('european_cities');
	
A SQL Query that can be used as the data source for layers and dataviews.
| Name | Description | 
|---|---|
| query | stringA SQL query containing a SELECT statement | 
	    carto.source.Base
    
        Example
1
2
	new carto.source.SQL('SELECT * FROM european_cities');
	
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.
| Name | Description | 
|---|---|
| query | stringThe sql query that will be the source of the data | 
A promise that will be fulfilled when the reload cycle is completed
Promise
	
                    
                    
                    
                A CartoCSS/TurboCarto style that can be applied to a carto.layer.Layer .
| Name | Description | 
|---|---|
| content | stringA CartoCSS string | 
	    carto.style.Base
    
        Example
1
2
3
4
5
6
7
	var style = new carto.style.CartoCSS(`
  #layer {
    marker-fill: #FABADA;
    marker-width: 10;
  }
`);
	
Set the CartoCSS/Turbocarto as a string.
| Name | Description | 
|---|---|
| newContent | stringA string containing the new cartocss/turbocarto style | 
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');
 });
	
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.
object
        
        
        
| Name | Description | 
|---|---|
| message | stringA short error description | 
| name | stringThe name of the error "CartoError" | 
| origin | stringWhere the error was originated: 'windshaft' | 'ajax' | 'validation' | 
| originalError | objectAn object containing the internal/original error | 
| stack | objectError stack trace | 
| type | stringError 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))
	
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);
});
	
Example
1
2
3
4
5
	// Listen when there is an error in a dataview
dataview.on('error', function (error) {
  console.error(error.message);
});