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

This documentation is intended for developers and describes specific methods from the latest version of the CARTO.js library.

cartodb.createVis

cartodb.createVis(map_id, vizjson_url[, options] [, callback])

Creates a visualization inside the map_id DOM object.

Arguments

Name Description
map_id a DOM object, for example $('#map') or a DOM id.
vizjson_url url of the vizjson object.
options  
|_ shareable add facebook and twitter share buttons.
|_ title adds a header with the title of the visualization.
|_ description adds description to the header (as you set in the UI).
|_ search adds a search control (default: true).
|_ zoomControl adds zoom control (default: true).
|_ loaderControl adds loading control (default: true).
|_ center_lat latitude where the map is initializated.
|_ center_lon longitude where the map is initializated.
|_ zoom initial zoom.
|_ cartodb_logo default to true, set to false if you want to remove the CARTO logo.
|_ infowindow set to false if you want to disable the infowindow (enabled by default).
|_ time_slider show an animated time slider with Torque layers. This option is enabled by default, as shown with time_slider: true value. To disable the time slider, use time_slider: false. See No Torque Time Slider - Example Code for an example.

For details about customizing the time slider, see the Torque.js documentation.
|_ layer_selector show layer selector (default: false).
|_ legends if it’s true legends are shown in the map.
|_ https if true, it makes sure that basemaps are converted to https when possible. If explicitly false, converts https maps to http when possible. If undefined, the basemap template is left as declared at urlTemplate in the viz.json.
|_ scrollwheel enable/disable the ability of zooming using scrollwheel (default enabled)
|_ fullscreen if true adds a button to toggle the map fullscreen
|_ mobile_layout if true enables a custom layout for mobile devices (default: false)
|_ force_mobile forces enabling/disabling the mobile layout (it has priority over mobile_layout argument)
|_ gmaps_base_type Use Google Maps as map provider whatever is the one specified in the viz.json”. Available types: ‘roadmap’, ‘gray_roadmap’, ‘dark_roadmap’, ‘hybrid’, ‘satellite’, ‘terrain’.
|_ gmaps_style Google Maps styled maps. See documentation.
|_ no_cdn true to disable CDN when fetching tiles
callback(vis,layers) if a function is specified, it is called once the visualization is created, passing vis and layers as arguments

Returns

A promise object. You can listen for the following events:

Event Description
done triggered when the visualization is created, vis is passed as the first argument and layers is passed as the second argument. Each layer type has different options, see layers section.
error triggered when the layer couldn’t be created. The error string is the first argument.

Example

1
2
3
4
5
var url = 'http://documentation.carto.com/api/v2/viz/2b13c956-e7c1-11e2-806b-5404a6a683d5/viz.json';

cartodb.createVis('map', url)
  .done(function(vis, layers) {
  });

cartodb.Vis

vis.getLayers()

Returns an array of layers in the map. The first is the base layer.

vis.addOverlay(options)

Adds an overlay to the map that can be either a tooltip or an infobox.

Arguments

Option Description
layer layer from the visualization where the overlay should be applied (optional)
type - tooltip (an infowindow that appears when you hover your mouse over a map feature)

- infobox (similar to a tooltip but always appears in the same fixed position that you define)

If no layer is provided, the overlay will be added to the first layer of the visualization. Extra options are available based on the specific UI function.

Returns

An overlay object, see vis.Overlays.

Example (Infowindow with Tooltip)

The following example displays how to enable infowindow interactivity with the mouse “hover” action. The hover action is referred to as a tooltip, and enables you to control the positioning.

layer.leafletMap.viz.addOverlay({
  type: 'tooltip',
  layer: sublayer,
  template: '<div class="cartodb-tooltip-content-wrapper"><img style="width: 100%" src=>, , , </div>', 
  position: 'bottom|right',
  fields: [{ name: 'name' }]
});

Tip: For a description of the infowindow specific parameters, see cartodb.vis.Vis.addInfowindow(_map, layer, fields [, options]_). Optionally, you can also use the cartodb.vis.Vis.addInfowindow function to define the click action for an infowindow.

vis.getOverlay(type)

Returns the first overlay with the specified type.

Example

1
var zoom = vis.getOverlay('zoom');

vis.getOverlays()

Returns a list of the overlays that are currently on the screen (see overlays description).

vis.getNativeMap()

Returns the native map object being used (e.g. a L.Map object for Leaflet).

vis.Overlays

An overlay is a control shown on top of the map.

Overlay objects are always created using the addOverlay method of a cartodb.Vis object.

An overlay is internally a Backbone.View so if you know how Backbone works you can use it. If you want to use plain DOM objects you can access overlay.el (overlay.$el for jQuery object).

cartodb.createLayer(map, layerSource [, options] [, callback])

With visualizations already created through the CARTO console, you can simply use the createLayer function to add them into your web pages. Unlike createVis, this method requires an already activated map object and it does not load a basemap for you.

Arguments

Name Description
map Leaflet L.Map object. The map should be initialized before calling this function.
layerSource contains information about the layer. It can be specified in multiple ways

Tip: See Multiple types of layers Source Object
options  
|_ https loads the layer as HTTPS. True forces the layer to load. See HTTPS support for example code.
|_ refreshTime if set, the layer is auto refreshed in milliseconds. See a refreshTime code example.

Tip: To refresh and display the latest data in seconds, include the seconds after the defined milliseconds in the code (i.e., refreshTime: 2000 // 2 seconds).
|_ infowindow set to false if you want to disable the infowindow (enabled by default). For details, see Creating an infowindow with the createLayer() function.
|_ tooltip set to false if you want to disable the tooltip (enabled by default). This option is specific for when you create a map using the CARTO Editor, and have enabled the tooltip (infowindow hover) option. This option disables the tooltip in createLayer.

See a tooltip code example.
|_ legends set to true to show legends in the map. For an example, see this CARTO.js example with legends disabled.
|_ time_slider show an animated time slider with Torque layers. This option is enabled by default, as shown with time_slider: true value. To disable the time slider, use time_slider: false. See a Torque Time Slider code example.

For details about customizing the time slider, see the Torque.js documentation.
|_ loop a boolean object that defines the animation loop with Torque layers. Default value is true. If false, the animation is paused when it reaches the last frame. For details about Torque, see the Torque.js documentation.
|_ layerIndex when the visualization contains more than one layer this index allows you to select what layer is created. Take into account that layerIndex == 0 is the base layer and that all the tiled layers (non animated ones) are merged into a single one. The default value for this option is 1 (usually tiled layers).

See layer.featureOver(_event, latlng, pos, data, layerIndex_) for details about binding functions to layer events.
|_ filter A string, or array of values, that specifies the type(s) of sublayers to be rendered if you are using multiple types of layer source objects (eg: `‘http’, ‘mapnik’). All non-torque layers (http and mapnik) will be rendered if this option is not present.

See a createLayer filter example.
|_ no_cdn set to true to disable CDN when fetching tiles. For a complete example of this code, see “odyssey_test.html”.
callback(layer) if a function is specified, it will be invoked after the layer has been created. The layer will be passed as an argument.

See the example of loading multiple layers from CARTO in a Leaflet Map.

Passing the url where the layer data is located

1
cartodb.createLayer(map, 'http://myserver.com/layerdata.json')

Passing the data directly

1
cartodb.createLayer(map, { layermetadata })

Returns

A promise object. You can listen for the following events:

Events Description
done triggered when the layer is created, the layer is passed as first argument. Each layer type has different options, see layers section.
error triggered when the layer couldn’t be created. The error string is the first argument.

You can call to addTo(map[, position]) in the promise so when the layer is ready it will be added to the map.

Example

cartodb.createLayer using a url

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var map;
var mapOptions = {
  zoom: 5,
  center: [43, 0]
};
map = new L.Map('map', mapOptions);

cartodb.createLayer(map, 'http://documentation.carto.com/api/v2/viz/2b13c956-e7c1-11e2-806b-5404a6a683d5/viz.json')
  .addTo(map)
  .on('done', function(layer) {
    layer
      .on('featureOver', function(e, latlng, pos, data) {
        console.log(e, latlng, pos, data);
      })
      .on('error', function(err) {
        console.log('error: ' + err);
      });
  }).on('error', function(err) {
    console.log("some error occurred: " + err);
  });

Layer metadata must take one of the forms of the Layer Source Object.


cartodb.CartoDBLayer

CartoDBLayer allows you to manage tiled layers from CARTO, and manage sublayers.

layer.clear()

Clears the layer. It should be invoked after removing the layer from the map.

layer.hide()

Hides the layer from the map.

layer.show()

Shows the layer in the map if it was previously added.

layer.toggle()

Toggles the visibility of the layer and returns a boolean that indicates the new status (true if the layer is shown, false if it is hidden)

layer.setOpacity(opacity)

Changes the opacity of the layer.

Arguments

Name Description
opacity value in range [0, 1]

layer.getSubLayer(layerIndex)

Gets a previously created sublayer. And exception is raised if no sublayer exists.

Arguments

Name Description
layerIndex 0 based index of the sublayer to get. Should be within [0, getSubLayerCount())

Returns

A SubLayer object.

Example

1
2
3
4
5
layer.getSubLayer(1).hide();

var sublayer = layer.getSubLayer(0);

sublayer.setSQL('SELECT * FROM table_name limit 10');

layer.getSubLayerCount()

Gets the number of sublayers in layer.

Returns

The number of sublayers.

Example

Hide layers using layer.getSubLayerCount

1
2
3
4
5
var num_sublayers = layer.getSubLayerCount();

for (var i = 0; i < num_sublayers; i++) {
  layer.getSubLayer(i).hide();
}

layer.createSubLayer(layerDefinition)

Adds a new data to the current layer. With this method, data from multiple tables can be easily visualized.

Arguments

Name Description
layerDefinition an object with the sql and cartocss that defines the data, should be like
1
2
3
4
5
{
  sql: "SELECT * FROM table_name",
  cartocss: "#layer { marker-fill: red; }",
  interactivity: 'cartodb_id, area, column' // optional
}

sql and cartocss are mandatory. An exception is raised if either of them are not present. If the interactivity is not set, there is no interactivity enabled for that layer (better performance). SQL and CartoCSS syntax should be correct. View the documentation for PostgreSQL and CartoCSS for more information. There are some restrictions in the SQL queries:

  • Must not write. INSERT, DELETE, UPDATE, ALTER and so on are not allowed (the query will fail)
  • Must not contain trailing semicolon

Returns

A SubLayer object.

Example

1
2
3
4
5
6
7
cartodb.createLayer(map, 'http://examples.carto.com/api/v2/viz/european_countries_e/viz.json', function(layer) {
  // add populated places points over the countries layer
  layer.createSubLayer({
    sql: 'SELECT * FROM ne_10m_populated_places_simple',
    cartocss: '#layer { marker-fill: red; }'
  });
}).addTo(map);

layer.invalidate()

Refreshes the data. If the data has been changed in the CARTO server those changes will be displayed. Nothing happens otherwise. Every time a parameter is changed in a sublayer, the layer is refreshed automatically, so there’s no need to call this method manually.

layer.setAuthToken(auth_token)

Sets the auth token that will be used to create the layer. Only available for private visualizations. An exception is raised if the layer is not being loaded with HTTPS. See Named Maps for more information.

Arguments

Name Description
auth_token string

Returns

The layer itself.

layer.setParams(key, value)

Sets the configuration of a layer when using Named Maps. It can be invoked in different ways.

Note: This function is not supported when using Named Maps for Torque.

Arguments

Name Description
key string
value string or number

Returns

The layer itself.

Example

1
2
3
layer.setParams('test', 10); // sets test = 10
layer.setParams('test', null); // unset test
layer.setParams({'test': 1, 'color': '#F00'}); // set more than one parameter at once

layer.setSQL()

Sets the ‘sql’ request to the user database that will create the layer from the fetched data

layer.setCartoCSS()

Sets the ‘cartocss’ attribute that will render the tiles to create the layer, based on the specified CartoCSS style


cartodb.SubLayerBase

sublayer.set(layerDefinition)

Sets sublayer parameters. Useful when more than one parameter needs to be changed.

Arguments

Name Description
layerDefinition an object with the sql and cartocss that defines the data

Returns

The layer itself.

Example

1
2
3
4
5
sublayer.set({
  sql: "SELECT * FROM table_name WHERE cartodb_id < 100",
  cartocss: "#layer { marker-fill: red }",
  interactivity: "cartodb_id, the_geom, magnitude"
});

sublayer.get(attr)

Gets the attribute for the sublayer, for example ‘sql’, ‘cartocss’.

Returns

The requested attribute or undefined if it’s not present.

sublayer.remove()

Removes the sublayer. An exception will be thrown if a method is called and the layer has been removed.

sublayer.show()

Shows a previously hidden sublayer. The layer is refreshed after calling this function.

sublayer.hide()

Removes the sublayer from the layer temporarily. The layer is refreshed after calling this function.

sublayer.toggle()

Toggles the visibility of the sublayer and returns a boolean that indicates the new status (true if the sublayer is visible, false if it is hidden)

sublayer.isVisible()

It returns true if the sublayer is visible.

cartodb.CartoDBSubLayer

This is a subclass of cartodb.SubLayerBase.

sublayer.getSQL()

Shortcut for get('sql')

sublayer.getCartoCSS()

Shortcut for get('cartocss')

sublayer.setSQL(sql)

Shortcut for set({'sql': 'SELECT * FROM table_name'})

sublayer.setCartoCSS(css)

Shortcut for set({'cartocss': '#layer {...}' })

sublayer.setInteractivity(‘cartodb_id, name, …‘)

Shortcut for set({'interactivity': 'cartodb_id, name, ...' })

Sets the columns which data will be available via the interaction with the sublayer.

sublayer.setInteraction(true)

Enables (true) or disables (false) the interaction of the layer. When disabled, featureOver, featureClick, featureOut, mouseover and mouseout are not triggered.

Arguments

Name Description
enable true if the interaction needs to be enabled.

sublayer.infowindow

sublayer.infowindow is a Backbone model where we modify the parameters of the infowindow.

Attributes

Name Description
template Custom HTML template for the infowindow. You can write simple HTML or use Mustache templates.
sanitizeTemplate By default all templates are sanitized from unsafe tags/attrs (e.g. <script>), set this to false to skip sanitization, or a function to provide your own sanitization (e.g. function(inputHtml) { return inputHtml })).
width Width of the infowindow (value must be a number).
maxHeight Max height of the scrolled content (value must be a number).

Tip: If you are customizing your infowindow with CARTO.js, reference the CSS library for the latest stylesheet code.

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
<div id="map"></div>

<script>
  sublayer.infowindow.set({
    template: $('#infowindow_template').html(),
    width: 218,
    maxHeight: 100
  });
</script>

<script type="infowindow/html" id="infowindow_template">
  <span> custom </span>
  <div class="cartodb-popup v2">
    <a href="#close" class="cartodb-popup-close-button close">x</a>

     <div class="cartodb-popup-content-wrapper">
       <div class="cartodb-popup-content">
         <img style="width: 100%" src="http://rambo.webcindario.com/images/18447755.jpg"></src>
         <!-- content.data contains the field info -->
         <h4></h4>
       </div>
     </div>
     <div class="cartodb-popup-tip-container"></div>
  </div>
</script>

Here is the complete example source code


cartodb.HttpSubLayer

This is a subclass of cartodb.SubLayerBase.

sublayer.setURLTemplate(urlTemplate)

Shortcut for set({'urlTemplate': 'http://{s}.example.com/{z}/{x}/{y}.png' })

sublayer.setSubdomains(subdomains)

Shortcut for set({'subdomains': ['a', 'b', '...'] })

sublayer.setTms(tms)

Shortcut for set({'tms': true|false })

sublayer.getURLTemplate

Shortcut for get('urlTemplate')

sublayer.getSubdomains

Shortcut for get('subdomains')

sublayer.getTms

Shortcut for get('tms')

sublayer.legend

sublayer.legend is a Backbone model with the information about the legend.

Attributes

Name Description
template Custom HTML template for the legend. You can write simple HTML.
title Title of the legend.
show_title Set this to false if you don’t want the title to be displayed.
items An array with the items that are displayed in the legend.
visible Set this to false if you want to hide the legend.

Vizjson

This is the spec for visjson:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
  {
     // required
     // follows the http://semver.org/ style version number
     "version": "0.1.0"
   
    // optional
    // default: [0, 0]
    // [lat, lon] where map is placed when is loaded. If bounds is present it is ignored
     "center": [0, 0],
   
    // optional
    // default: 4
    "zoom": 4,

    // optional
    // default: null
    // bounds the map show at the beginning. If center and/or zoom are present
    // they are ignored
    "bounds": [
      [-1, -1], // sw lat, lon
      [ 1,  1]  // ne lat, lon
    ],

    // optional
    // visualization title
    // default: ''
    "title": ""

    // optional
    // visualization description
    // default: ''
    "description": ""

    // optional
    // visualization description
    // default: ''
    url: "http://javi.carto.com/tables/20343",

    // mandatory 
    map_provider: "leaflet",

     // optional
     // default: []
     // contains the layers
     "layers": [
      // xyz tiled
      {
       type: "tiled"
       order: 0,
       options: {
          name: "CartoDB Flat Blue",
          urlTemplate: "http://{s}.api.cartocdn.com/base-flatblue/{z}/{x}/{y}.png",
          maxZoom: 10,
          attribution: "©2013 CARTO <a href='https://carto.com' target='_blank'>Terms of use</a>",
         },
       },
       
       // plain color layer
       {
        order: 0,
        type: "background"
        options: {
          color: "#eeeeee",
          image: "",
          maxZoom: 28,
          id: 59811,
        },
       },
       
       // cartodb layer (deprecated)
       {
         type: 'cartodb',
         order: 1,
         options: {
            type: "CartoDB",
            active: true,
            opacity: 0.99,
            interactivity: "cartodb_id",
            debug: false,
            tiler_domain: "cartodb.com",
            tiler_port: "443",
            tiler_protocol: "https",
            sql_domain: "cartodb.com",
            sql_port: "443",
            sql_protocol: "https",
            extra_params: {
                cache_policy: "persist",
                cache_buster: 1364213207314
            },
            cdn_url: "",
            auto_bound: false,
            visible: true,
            style_version: "2.1.1",
            table_name: "counties_ny_export",
            user_name: "javi",
            query_wrapper: null
         },
         infowindow: {
            fields: [{
                name: "fips",
                title: true,
                position: 2
            },
            ...
            ],
            template_name: '...',
            template: 'html template'
         }
       },
       
       // layergroup
       {
         type: 'layergroup',
         order: 1,
         options: {
            type: "CartoDBLayerGroup",
            tiler_domain: "cartodb.com",
            tiler_port: "443",
            tiler_protocol: "https",
            sql_domain: "cartodb.com",
            sql_port: "443",
            sql_protocol: "https",
            user_name: "javi",
            layerdefinition: see https://github.com/Vizzuality/Windshaft/wiki/Multilayer-API
         },
         infowindow: {
            fields: [{
                name: "fips",
                title: true,
                position: 2
            },
            ...
            ],
            template_name: '...',
            template: 'html template'
         }
       },

       // named-map 
       {
         type: 'namedmap',
         order: 1,
         options: {
            type: "namedmap",
            tiler_domain: "cartodb.com",
            tiler_port: "443",
            tiler_protocol: "https",
            user_name: "javi",
            require_password: true/false,
            cdn_url: {
                http: "api.cartocdn.com",
                https: "cartocdn.global.ssl.fastly.net"
            },
            named_map: {
                name: 'test',
                params: {
                    //template params
                    color: '#FFF',
                    other_var: 1
                },
                layers: [{
                    infowindow: '',
                    legend: '',
                    layer_name: 'name_of_layer',
                    interactivity: 'column1, column2, ...',
                    visible: true/false
                    }, {...}

                ],
				stat_tag: "a5c626a0-a29f-11e4-bee0-010c4c326911"
            },
         }
       },
       
       // torque
       {
         type: 'torque',
         order: XX,
         options: {
            stat_tag: "d4a5c7e4-4ad6-11e3-ab17-3085a9a9563c",
            tiler_protocol: "http",
            tiler_domain: "cartodb.com",
            tiler_port: "80",
            cdn_url: {
              http: "api.cartocdn.com",
              https: "cartocdn.global.ssl.fastly.net"
            },
            query: null,
            table_name: "sensor_log_2013_10_27_12_01",
            user_name: "javi", // CARTO username
            cartocss: "valid cartocss",
            named_map: { //if this key is present named_map is used, if not it means it's an anonymous map
                name: 'test',
                layer_index: 1, // layer_index inside Named Map
                params: {
                    //template params
                    color: '#FFF',
                    other_var: 1
                },
            }
         }
       },
     ],

     overlays: [{
       type: 'zoom',
       template: 'mustache template'
       options: {
         ... other options

       }
     }],
   
  }