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
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.
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://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');
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.
class
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: 'http://{username}.your.carto.instance'
});
Fired when a request to the server completed successfully.
Add a dataview to the client.
dataview |
carto.dataview.Base
The 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);
}):
Add multipe dataviews to the client.
dataviews |
carto.dataview.Base
Array
An array with the dataviews to be added |
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);
}):
Add a layer to the client. If the layer id already exists in the client this method will throw an error.
layer |
carto.layer.Base
The 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);
});
Add multiple layers to the client at once.
layers |
carto.layer.Base
Array
An array with the layers to be added. Note that ([A, B]) displays B as the top layer. |
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);
});
Get all the dataviews from the client.
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();
Return a google.maps.MapType that groups all the layers that have been added to this client.
map |
google.maps.Map
The 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
carto.layer.Base
Array
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.
options |
object
L.TileLayer options. |
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.
layer |
carto.layer.Base
The layer to be moved |
toIndex |
carto.layer.Base
The 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.
dataview |
carto.dataview.Base
The 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.
layer |
carto.layer.Base
The 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);
});
Remove multiple layers from the client.
layers |
carto.layer.Base
Array
An array with the layers to be removed |
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);
});
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.
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);
})
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
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 dataview column where the dataview is applied.
Current dataview column
string
Return the current source where the dataview gets the data from.
Current source object
carto.source.Base
Return true is the current status is error.
boolean
Check if a filter exists in the dataview.
filter |
carto.filter.Base
|
this
carto.dataview.Base
Return true if the dataview is enabled.
boolean
Return true is the current status is loaded.
boolean
Return true is the current status is loading.
boolean
object
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
});
A category dataview is used to aggregate data performing a operation.
This is similar to a group by SQL operation, for example:
The following code is the CARTO.js equivalent:
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
class
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)
|
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
Return the current categories limit.
Current dataview limit
number
Return the current dataview operationColumn.
Current dataview operationColumn
string
Set the dataview operation.
operation |
carto.operation
|
this
carto.dataview.Category
Set the dataview operationColumn.
operationColumn |
string
|
this
carto.dataview.Category
object
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
|
object
Name |
Description |
---|---|
group |
boolean
Category is a group |
name |
string
Category name |
value |
number
Category 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.
class
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)
|
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.
operation |
carto.operation
|
this
carto.dataview.Formula
Object containing formula data
object
Name |
Description |
---|---|
nulls |
number
Number of null values in the column |
operation |
string
Operation used |
result |
number
Result of the operation |
A histogram is used to represent the distribution of numerical data.
See https://en.wikipedia.org/wiki/Histogram .
class
source |
carto.source.Base
The source where the dataview will fetch the data |
||||||||
column |
string
The 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
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);
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 current number of bins.
Current number of bins
number
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}
Distribution type of current data
string
Return the upper limit of the bins' range
Current value of end
number
Return the lower limit of the bins' range
Current value of start
number
Set the lower and upper limit of the bins range
start |
number
|
end |
number
|
this
carto.dataview.Histogram
Object containing histogram data.
object
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 |
Enum for dataview status values.
string
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 |
Enum for dataview time aggregations.
string
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 |
A dataview to represent an histogram of temporal data allowing to specify the granularity of the temporal bins.
class
source |
carto.source.Base
The source where the dataview will fetch the data |
||||||||
column |
string
The 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
Return the current time offset in hours.
Current time offset
number
Return the current local timezone flag.
Current local timezone flag
boolean
Set time aggregation.
aggregation |
carto.dataview.timeAggregation
|
this
carto.dataview.TimeSeries
Set the local timezone flag. If enabled, the time offset is overriden by the user's local timezone.
enable | |
localTimezone |
boolean
|
this
carto.dataview.TimeSeries
object
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 |
Object containing time series data.
object
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 |
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()
.
class
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);
Base filter object
class
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.
class
carto.filter.Base
Fired when bounds have changed. Handler gets a parameter with the new bounds.
carto.filter.Bounds
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.
class
map |
google.maps.map
The 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.
class
map |
L.Map
The 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 |
number
West coordinate |
south |
number
South coordinate |
east |
number
East coordinate |
north |
number
North coordinate |
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.
class
column |
string
The column which the filter will be performed against |
||||||||||||||||||||||||||||||
filters |
|
||||||||||||||||||||||||||||||
options |
(Optional)
|
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);
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);
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);
Remove all conditions from current filter
Set any of the filter conditions, overwriting the previous one.
filterType |
string
The filter type that you want to set.
|
filterValue |
string
The value of the filter. Check types in carto.filter.Category |
Set filter conditions, overriding all the previous ones.
filters |
object
Object containing all the new filters to apply. Check filter options in carto.filter.Category . |
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.
class
carto.filter.Base
Fired when circle filter has changed. Handler gets a parameter with the new circle.
carto.filter.CircleData
object
Name |
Description |
---|---|
lat |
number
Center Latitude WGS84 |
lng |
number
Center Longitude WGS84 |
radius |
number
Radius in meters |
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.
class
carto.filter.Base
Add a new filter to collection
Get the number of added filters
Number of contained filters
number
Get added filters
Added filters
Array
Remove an existing filter from collection
The removed element
carto.filter.Range
|
carto.filter.Category
|
carto.filter.AND
|
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()
.
class
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);
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.
class
carto.filter.Base
Fired when polygon filter has changed. Handler gets a parameter with the new polygon.
carto.filter.PolygonData
Return the current polygon data
Current polygon data, expressed as a GeoJSON geometry fragment
carto.filter.PolygonData
object
Name |
Description |
---|---|
type |
string
Geometry type, Just 'Polygon' is valid |
coordinates |
Array
Array of coordinates [lng, lat] as defined in GeoJSON geometries |
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.
class
column |
string
The column to filter rows |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
filters |
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
(Optional)
|
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);
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);
Remove all conditions from current filter
Set any of the filter conditions, overwriting the previous one.
filterType |
string
The filter type that you want to set.
|
filterValue |
string
The value of the filter. Check types in carto.filter.Range |
Set filter conditions, overriding all the previous ones.
filters |
object
Object containing all the new filters to apply. Check filter options in carto.filter.Range . |
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.
class
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.
class
source | |
layer | |
options |
Event object for feature events triggered by carto.layer.Layer .
object
Name |
Description |
---|---|
latLng |
LatLng
Object with coordinates where interaction took place |
data |
object
Object 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 .
class
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)
|
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);
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
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 });
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}`);
});
Move the layer to the back.
Promise
Move the layer to the front.
Promise
Get the columns available in featureClicked events.
Column names available in featureClicked events
string Array
Get the columns available in featureOver events.
Column names available in featureOver events
string Array
Return
true
if the layer is not visible and
false
when visible.
A boolean value indicating the layer's visibility
boolean
Return true if the layer has interactivity.
A boolean value indicating the layer's interactivity
boolean
Return true if the layer is visible and false when not visible.
A boolean value indicating the layer's visibility
boolean
Set new columns for featureClick events.
columns |
string Array
An array containing column names |
Promise
Set new columns for featureOver events.
columns |
string Array
An array containing column names |
Promise
Set the layer's order.
index |
number
new order index for the layer. |
Promise
Base metadata object
class
type | |
rule |
Return the column of the metadata
string
Return the property of the metadata
string
Return the property of the metadata
string
Return the type of the metadata
string
object
Name |
Description |
---|---|
min |
number
The minimum range value |
max |
number
The maximum range value |
value |
number
|
string
The value of the bucket |
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);
class
rule |
object
Rule with the cartocss metadata |
carto.layer.metadata.Base
Return the average of the column
number
Return the maximum value in the ranges
number
Return the minimum value in the ranges
number
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);
class
rule |
object
Rule with the cartocss metadata |
carto.layer.metadata.Base
Return the default value
string
object
Name |
Description |
---|---|
name |
number
|
string
The name of the category |
value |
string
The value of the category |
Event fired by carto.layer.Layer when the style contains any TurboCarto ramp.
object
Name |
Description |
---|---|
styles |
carto.layer.metadata.Base
Array
List of style metadata objects |
Enum for operation values.
string
Name |
Description |
---|---|
COUNT |
string
Number of elements |
SUM |
string
Sum |
AVG |
string
Average |
MAX |
string
Maximum |
MIN |
string
Minimum |
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.
class
Add new filter to the source
Add new filters to the source
filters |
Array
|
Get added filters
Added filters
Array
Remove an existing filter from source
Remove existing filters from source
filters |
Array
|
A Dataset that can be used as the data source for layers and dataviews.
class
tableName |
string
The name of an existing table |
carto.source.Base
Example
1
2
new carto.source.Dataset('european_cities');
Return the table name being used in this Dataset object.
The table name being used in this Dataset object
string
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.
tableName |
string
The name of an existing table |
A promise that will be fulfilled when the reload cycle is completed
Promise
A SQL Query that can be used as the data source for layers and dataviews.
class
query |
string
A SQL query containing a SELECT statement |
carto.source.Base
Example
1
2
new carto.source.SQL('SELECT * FROM european_cities');
Get the query being used in this SQL source.
The query being used in this SQL object
string
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.
query |
string
The sql query that will be the source of the data |
A promise that will be fulfilled when the reload cycle is completed
Promise
Base style object.
class
A CartoCSS/TurboCarto style that can be applied to a carto.layer.Layer .
class
content |
string
A 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;
}
`);
Get the current CartoCSS/TurboCarto style as a string.
The TurboCarto style for this CartoCSS object
string
Set the CartoCSS/Turbocarto as a string.
newContent |
string
A string containing the new cartocss/turbocarto style |
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');
});
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 |
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))
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);
});
object
Name |
Description |
---|---|
lat |
number
Latitude |
lng |
number
Longitude |