This commit is contained in:
zhongjin
2020-06-15 12:07:54 +08:00
parent 610ed21a90
commit a96ef233c9
444 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,225 @@
## Getting Started
The simplest way to use a visualization created in CARTO on an external site is as follows:
```html
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
...
<div id="map"></div>
...
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
<script>
// get the viz.json url from the CARTO Editor
// - click on visualize
// - create new visualization
// - make visualization public
// - click on publish
// - go to API tab
window.onload = function() {
cartodb.createVis('map', 'http://documentation.carto.com/api/v2/viz/2b13c956-e7c1-11e2-806b-5404a6a683d5/viz.json');
}
</script>
```
[Here is the complete example source code](https://github.com/CartoDB/cartodb.js/blob/develop/examples/easy.html)
### Using the CARTO.js Library
CARTO.js can be used to embed a visualization you have designed using CARTO's user interface, or to dynamically create visualizations from scratch, using your data. If you want to create new maps on your webpage, jump to [Creating a visualization from scratch](#creating-a-visualization-from-scratch). If you already have maps on your webpage and want to add CARTO visualizations to them, read [Adding CARTO layers to an existing map](#adding-carto-layers-to-an-existing-map).
You can also use the CARTO APIs to create visualizations programmatically. This can be useful when the visualizations react to user interactions. To read more about it, jump to [Creating visualizations at runtime](#creating-visualizations-at-runtime).
To start using CARTO.js, paste this piece of code within the HEAD tags of your HTML:
```html
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
```
#### Other Mapping Libraries
We have also made it easy for you to build maps using the mapping library of your choice. Whether you are using [Leaflet](#leaflet-integration) or something else, our CARTO.js code remains the same. This makes our API documentation simple and straightforward. It also makes it easy for you to consistently develop, or maintain, multiple maps online.
_**Note:** CARTO.js automatically includes dependencies from other mapping libraries (such as Leaflet, jQuery, Mustache, Underscore, and so on). You do not have to manually include these libraries, or worry about other mapping library version control, when you are using CARTO.js. If you need to see which version of other mapping libraries are included, view the [vendor](https://github.com/CartoDB/cartodb.js/tree/3.15.9/vendor) folder for each CARTO.js release._
### Creating a Visualization from Scratch
This is the easiest way to quickly get a CARTO map onto your webpage. Use this method when there is no map in your application, and you want to add the visualization to hack over it. CARTO.js handles all the details of loading a map interface, basemap, and your CARTO visualization.
You can start by giving CARTO.js the DIV ID from your HTML where you want to place your map, and the viz.json URL of your visualization (which you can get from the [Publish your map](http://docs.carto.com/carto-editor/maps/#publish-and-share-your-map) options).
```javascript
cartodb.createVis('map', 'http://documentation.carto.com/api/v2/viz/2b13c956-e7c1-11e2-806b-5404a6a683d5/viz.json');
```
Thats it! No need to create the map instance, insert controls, or load layers. CARTO.js takes care of this for you.
#### VizJSON Support
The viz.json file tells CARTO.js all the information about your map, including the style you want to use for your data and the filters you want to apply with SQL. The viz.json file is served with each map you create in your CARTO account.
Although the viz.json file stores all your map settings, all these settings can be easily customized with CARTO.js. If you want to modify the result after instantiating your map with the viz.json, reference the CARTO.js API [available methods](#api-methods). For example, you can also use the returned layer to build more functionality (show/hide, click, hover, custom infowindows):
```javascript
cartodb.createVis('map', 'http://documentation.carto.com/api/v2/viz/2b13c956-e7c1-11e2-806b-5404a6a683d5/viz.json')
.done(function(vis, layers) {
// layer 0 is the base layer, layer 1 is cartodb layer
// when setInteraction is disabled featureOver is triggered
layers[1].setInteraction(true);
layers[1].on('featureOver', function(e, latlng, pos, data, layerNumber) {
console.log(e, latlng, pos, data, layerNumber);
});
// you can get the native map to work with it
var map = vis.getNativeMap();
// now, perform any operations you need, e.g. assuming map is a L.Map object:
// map.setZoom(3);
// map.panTo([50.5, 30.5]);
});
```
**Tip:** You can download a viz.json from any visualization you have created and inspect it with a text editor, or view it in your browser if you have a JSON viewer. If you are unfamiliar with the JSON file format, view the [official JSON website](http://json.org/) for more information.
### Adding CARTO Layers to an Existing Map
In case you already have a map instantiated on your page, you can simply use the [createLayer](https://carto.com/docs/carto-engine/carto-js/api-methods/#cartodbcreatelayermap-layersource--options--callback) method to add new CARTO layers to it. This is particularly useful when you have more things on your map apart from CARTO layers or you have an application where you want to integrate CARTO layers.
Below, you have an example using a previously instantiated Leaflet map.
```html
<div id="map_canvas"></div>
<script>
var map = new L.Map('map_canvas', {
center: [0,0],
zoom: 2
});
cartodb.createLayer(map, 'http://documentation.carto.com/api/v2/viz/2b13c956-e7c1-11e2-806b-5404a6a683d5/viz.json')
.addTo(map)
.on('done', function(layer) {
//do stuff
})
.on('error', function(err) {
alert("some error occurred: " + err);
});
</script>
```
[Here is the complete example source code](https://github.com/CartoDB/cartodb.js/blob/develop/examples/leaflet.html)
### Creating Visualizations at Runtime
All CARTO services are available through the API, which basically means that you can create a new visualization without doing it before through CARTO Editor. This is particularly useful when you are modifying the visualization depending on user interactions that change the SQL to get the data or CartoCSS to style it. Although this method requires more programming skills, it provides all the flexibility you might need to create more dynamic visualizations.
When you create a visualization using the CARTO website, you automatically get a viz.json URL that defines it. When you want to create the visualization via JavaScript, you don't always have a viz.json. You will need to pass all the required parameters to the library so that it can create the visualization at runtime and display it on your map. It is pretty simple.
```javascript
// create a layer with 1 sublayer
cartodb.createLayer(map, {
user_name: 'username',
type: 'cartodb',
sublayers: [{
sql: "SELECT * FROM table_name",
cartocss: '#table_name {marker-fill: #F0F0F0;}'
}]
})
.addTo(map) // add the layer to our map which already contains 1 sublayer
.done(function(layer) {
// create and add a new sublayer
layer.createSubLayer({
sql: "SELECT * FROM table_name limit 200",
cartocss: '#table_name {marker-fill: #F0F0F0;}'
});
// change the query for the first layer
layer.getSubLayer(0).setSQL("SELECT * FROM table_name limit 10");
});
```
Want more information? [See the complete list of API methods](https://carto.com/docs/carto-engine/carto-js/api-methods/#api-methods).
---
### Leaflet Integration
If you want to use [Leaflet](http://leafletjs.com), it gets even easier. CARTO.js handles loading all the [necessary libraries for you](http://docs.carto.com/carto-engine/carto-js/getting-started/#other-mapping-libraries)! Just include CartoDB.js and CartoDB.css in the HEAD of your website and you are ready to go! The CartoDB.css document is not mandatory. However, if you are making a map, and are not familiar with writing your own CSS for the various needed elements, it can help you jumpstart the process. Using Leaflet is as simple as adding the main JavaScript library:
```html
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
```
---
### HTTPS Support
You can use all the functionality of CARTO.js with HTTPs support. Be sure to use https when importing both the JS library and the CSS file. You will also need to use HTTPs in the viz.json URL you pass to `createVis` or `createLayer`.
```html
<div id="map"></div>
<link rel="stylesheet" href="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.js"></script>
<script>
var map = new L.Map('map', {
center: [0,0],
zoom: 2
})
cartodb.createLayer(map, 'https://examples.carto.com/api/v1/viz/15589/viz.json', { https: true })
.addTo(map)
.on('error', function(err) {
alert("some error occurred: " + err);
});
</script>
```
### Using a Different Host
CARTO.js sends all requests to the carto.com domain by default. If you are running your own instance of CARTO, you can change the URLs to specify a different host.
A different host can be configured by using ``sql_api_template`` and ``maps_api_template`` in the ``options`` parameter
for any ``cartodb`` function call.
The format of these templates is as follows:
```javascript
sql_api_template: 'https://{user}.test.com'
```
CARTO.js will replace ``{user}``.
Note that you do not need to set the path to the endpoint, CARTO.js sets it automatically.
### Loading Listener Events
To async portions of the CARTO.js library, the [`createLayer`](http://docs.carto.com/carto-engine/carto-js/api-methods/#cartodbcreatelayermap-layersource--options--callback) and [`createVis`](http://docs.carto.com/carto-engine/carto-js/api-methods/#cartodbcreatevis) API Methods trigger two important listener events for you to take advantage of:
- **done**, tells your code that the library has successfully read the information from the viz.json, and loaded the layer you requested.
- **error**, tells you that something did not go as expected when trying to load the requested layer:
```javascript
cartodb.createLayer(map, 'http://examples.carto.com/api/v1/viz/0001/viz.json')
.addTo(map)
.on('done', function(layer) {
alert(CartoDB layer loaded!);
}).on('error', function(err) {
alert("some error occurred: " + err);
});
```
**Note:** For information about active layer events, which are triggered by layers on your webpage that are already loaded, see [Events](http://docs.carto.com/carto-engine/carto-js/events/).
### CARTO.js Usage Examples
The best way to start learning about the library is by taking a look at some of the examples below:
+ An easy example using the library - ([view live](http://cartodb.github.com/carto.js/examples/v3/easy.html) / [source code](https://github.com/CartoDB/cartodb.js/blob/develop/examples/easy.html)).
+ Leaflet integration - ([view live](http://cartodb.github.com/carto.js/examples/v3/leaflet.html) / [source code](https://github.com/CartoDB/cartodb.js/blob/develop/examples/leaflet.html)).
+ Customizing infowindow data - ([view live](http://cartodb.github.com/carto.js/examples/v3/custom_infowindow.html) / [source code](https://github.com/CartoDB/cartodb.js/blob/develop/examples/custom_infowindow.html)).
+ An example using a layer selector - ([view live](http://cartodb.github.com/carto.js/examples/v3/layer_selector.html) / [source code](https://github.com/CartoDB/cartodb.js/blob/develop/examples/layer_selector.html)).

View File

@@ -0,0 +1,100 @@
## Layer Source Object
### Standard Layer Source Object (_type: 'cartodb'_)
Used for most maps with tables that are set to public or public with link.
##### Arguments
Layer Source Objects are defined with the [Layergroup Configurations](http://docs.carto.com/carto-engine/maps-api/mapconfig/#layergroup-configurations).
Name |Description
--- | ---
type | A string value that defines the layer type. Required.
options | Options vary, depending on the `type` of layer source you are using:
--- | ---
&#124;_ `mapnik`| See [Mapnik Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#mapnik-layer-options).
&#124;_ `cartodb` | An alias for Mapnik (for backward compatibility).
&#124;_ `torque` | See [Torque Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#torque-layer-options).
&#124;_ `http` | See [HTTP Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#http-layer-options).
&#124;_ `plain` | See [Plain Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#plain-layer-options).
&#124;_ `named` | See [Named Map Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#named-map-layer-options).
##### Example
```javascript
{
user_name: 'your_user_name', // Required
type: 'cartodb', // Required
sublayers: [{
sql: "SELECT * FROM table_name", // Required
cartocss: '#table_name {marker-fill: #F0F0F0;}', // Required
interactivity: "column1, column2, ...", // Optional
},
{
sql: "SELECT * FROM table_name", // Required
cartocss: '#table_name {marker-fill: #F0F0F0;}', // Required
interactivity: "column1, column2, ...", // Optional
},
...
]
}
```
For other layer source definitions, see [this example](https://github.com/CartoDB/cartodb.js/blob/4ba5148638091fd2c194f48b2fa3ed6ac4ecdb23/examples/layer_definition.html).
### Named Maps Layer Source Object (_type: 'namedmap'_)
Used for making public maps with private data. See [Named Maps](http://docs.carto.com/carto-engine/maps-api/named-maps/) for more information.
##### Example
```javascript
{
user_name: 'your_user_name', // Required
type: 'namedmap', // Required
named_map: {
name: 'name_of_map', // Required
// Optional
layers: [{
layer_name: "sublayer0", // Optional
interactivity: "column1, column2, ..." // Optional
},
{
layer_name: "sublayer1",
interactivity: "column1, column2, ..."
},
...
],
// Optional
params: {
color: "hex_value",
num: 2
}
}
}
```
### Multiple types of layers Source Object
`cartodb.createLayer` combining multiple types of layers and setting a filter
##### Example
```javascript
cartodb.createLayer(map, {
user_name: 'examples',
type: 'cartodb',
sublayers: [
{
type: "http",
urlTemplate: "http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png",
subdomains: [ "a", "b", "c" ]
},
{
sql: 'select * from country_boundaries',
cartocss: '#layer { polygon-fill: #F00; polygon-opacity: 0.3; line-color: #F00; }'
},
],
}, { filter: ['http', 'mapnik'] })
```

View File

@@ -0,0 +1,135 @@
## Events
You can bind custom functions to layer events by adding listeners and callbacks to the async portions of the CARTO.js library. Active layer events are triggered by layers on your webpage that are already loaded (**Tip:** these are the `createLayer` and `createVis` functions that return the _done_ event. For details, see [Loading Events](http://docs.carto.com/carto-engine/carto-js/getting-started/#loading-listener-events)). Each event requires the layer to include an **interactivity** layer. This is useful for integrating your website with your maps, adding events for mouseovers and click events.
**Note:** Be mindful of using these events, as these functions can get costly if you have a lot of features on a map.
### layer
#### layer.featureOver(_event, latlng, pos, data, layerIndex_)
Triggered when the user mouse hovers on any feature.
##### Callback arguments
Name |Description
--- | ---
event | Browser mouse event object.
latlng | Array with the `LatLng ([lat,lng])` where the layer was clicked.
pos | Object with x and y position in the DOM map element.
data | The CARTO data of the clicked feature with the `interactivity` param.
layerIndex | the `layerIndex` where the event happened.
##### Example
```javascript
layer.on('featureOver', function(e, latlng, pos, data, subLayerIndex) {
console.log("mouse over polygon with data: " + data);
});
```
#### layer.featureOut(_layerIndex_)
Triggered when the user hovers out any feature. For example, you might want to use this event if you highlight polygons on mouseover and need a way to know when to remove the highlighting after the mouse has left.
##### Example
```javascript
layer.on('featureOut', function(e, latlng, pos, data, layer) {
console.log("mouse left polygon with data: " + data);
});
```
#### layer.featureClick(_event, latlng, pos, data, layerIndex_)
Triggered when when the user clicks on a feature of a layer.
##### Example
```javascript
layer.on('featureClick', function(e, latlng, pos, data, layer) {
console.log("mouse clicked polygon with data: " + data);
});
```
##### Callback arguments
Same as `featureOver`.
#### layer.mouseover()
Triggered when the mouse enters in **any** feature. Useful to change the cursor while hovering.
#### layer.mouseout()
Triggered when the mouse leaves all the features. Useful to revert the cursor after hovering.
##### Example
```javascript
layer.on('mouseover', function() {
cursor.set('hand')
});
layer.on('mouseout', function() {
cursor.set('auto')
});
```
#### layer.loading()
Triggered when the layer or any of its sublayers are about to be loaded. This is also triggered when any properties are changed but not yet visible.
##### Example
```javascript
layer.on("loading", function() {
console.log("layer about to load");
});
layer.getSubLayer(0).set({
cartocss: "#export { polygon-opacity: 0; }"
});
```
#### layer.load()
Triggered when the layer or its sublayers have been loaded. This is also triggered when any properties are changed and visible.
##### Example
```javascript
layer.on("load", function() {
console.log("layer loaded");
});
layer.getSubLayer(0).set({
cartocss: "#export { polygon-opacity: 0; }"
});
```
---
### subLayer
#### sublayer.featureOver(_event, latlng, pos, data, layerIndex_)
Same as `layer.featureOver()` but sublayer specific.
##### Callback arguments
Same as `layer.featureOver()`.
#### sublayer.featureClick(_event, latlng, pos, data, layerIndex_)
Same as `layer.featureClick()` but sublayer specific.
##### Callback arguments
Same as `layer.featureClick()`.
#### sublayer.mouseover()
Same as `layer.mouseover()` but sublayer specific.
#### sublayer.mouseout()
Same as `layer.mouseover()` but sublayer specific.

View File

@@ -0,0 +1,82 @@
## Specific UI Functions
There are a few functions in CARTO.js for creating, enabling, and disabling pieces of the user interface.
### vis.addOverlay(tooltip)
A tooltip is an infowindow that appears when you hover your mouse over a map feature with [`vis.addOverlay(options)`](http://docs.carto.com/carto-engine/carto-js/api-methods/#visaddoverlayoptions). A tooltip appears where the mouse cursor is located on the map. You can customize the position of how the tooltip appears by defining the position options.
##### Example
```javascript
var tooltip = vis.addOverlay({
type: 'tooltip',
template: '<p>{{variable}}</p>' // mustache template
width: 200,
position: 'bottom|right', // top, bottom, left and right are available
fields: [{ name: 'name', population: 'pop2005' }]
});
```
**Note:** If you are using `createLayer` for a map object that contains an enabled tooltip, you can disable the tooltip by applying the `false` value. See the [cartodb.createLayer(map, layerSource [, options] [, callback])](https://carto.com/docs/carto-engine/carto-js/api-methods/#cartodbcreatelayermap-layersource--options--callback) `tooltip` description for how to enable/disable an interactive tooltip.
### vis.addOverlay(infobox)
Similar to a tooltip, an infobox displays a small box when you hover your mouse over a map feature. When viewing an infobox on a map, _the position of the infobox is fixed_, and always appears in the same position; depending on how you defined the position values for the infobox.
##### Example
```javascript
var infoBox = layer.leafletMap.viz.addOverlay({
type: 'infobox',
template: '<p>{{name_to_display}}</p>',
width: 200, // width of the box
position: 'bottom|right' // top, bottom, left and right are available
});
```
### cartodb.vis.Vis.addInfowindow(_map, layer, fields [, options]_)
Infowindows provide additional interactivity for your published map, controlled by layer events. It enables interaction and overrides the layer interactivity. A pop-up information window appears when a viewer clicks on a map feature.
##### Arguments
Option | Description
--- | ---
map | native map object or leaflet.
layer | cartodb layer (or sublayer).
fields | array of column names.<br /><br />**Note:** This tells CARTO what columns from your dataset should appear in your infowindow.
options |
--- | ---
&#124;_ infowindowTemplate | allows you to set the HTML of the template.
&#124;_templateType | indicates the type of template ([`Mustache` template](http://mustache.github.io/mustache.5.html) or `Underscore` template placeholders).
**Tip:** See [How can I use CARTO.js to create and style infowindows?](http://docs.carto.com/faqs/infowindows/#how-can-i-use-cartojs-to-create-and-style-infowindows) for an overview of how to create infowindows.
##### Returns
An infowindow object, see [sublayer.infowindow](http://docs.carto.com/carto-engine/carto-js/api-methods/#sublayerinfowindow)
##### Example
The following example displays how to enable infowindow interactivity with the "click" action. This is the default for infowindows.
{% highlight html %}
cartodb.vis.Vis.addInfowindow(map, sublayer, ['cartodb_id', 'lat', 'lon', 'name'],{
infowindowTemplate: $('#infowindow_template').html(),
templateType: 'mustache'
});
{% endhighlight %}
##### Example (Infowindow with Tooltip)
The following example displays how to enable infowindow interactivity with the mouse "hover" action. This is referred to as a tooltip, and is defined with [`vis.addOverlay`](http://docs.carto.com/carto-engine/carto-js/api-methods/#visaddoverlayoptions).
{% highlight html %}
layer.leafletMap.viz.addOverlay({
type: 'tooltip',
layer: sublayer,
template: '<div class="cartodb-tooltip-content-wrapper"><img style="width: 100%" src={{_url}}>{{name}}, {{age}}, {{city}}, {{country}}</div>',
position: 'bottom|right',
fields: [{ name: 'name' }]
});
{% endhighlight %}

View File

@@ -0,0 +1,93 @@
## Getting Data with SQL
CARTO offers a powerful SQL API for you to query and retreive data from your CARTO tables. CARTO.js offers a simple to use wrapper for sending those requests and using the results.
### cartodb.SQL
`cartodb.SQL` is the tool you will use to access data you store in your CARTO tables. This is a really powerful technique for returning things like: **items closest to a point**, **items ordered by date**, or **GeoJSON vector geometries**. Its all powered with SQL and our tutorials will show you how easy it is to begin with SQL.
##### Arguments
Name | Description
--- | ---
format | should be GeoJSON.
dp | float precision.
jsonp | if jsonp should be used instead of CORS. This param is enabled if the browser does not support CORS.
These arguments will be applied to all the queries performed by this object. If you want to override them for one query see **execute** options.
##### Example
```javascript
var sql = new cartodb.SQL({ user: 'cartodb_user' });
sql.execute("SELECT * FROM table_name WHERE id > {{id}}", { id: 3 })
.done(function(data) {
console.log(data.rows);
})
.error(function(errors) {
// errors contains a list of errors
console.log("errors:" + errors);
})
```
### sql.execute(_sql [,vars][, options][, callback]_)
It executes a sql query.
##### Arguments
Name |Description
--- | ---
sql | a string with the sql query to be executed. You can specify template variables like {{variable}} which will be filled with `vars` object.
vars | a map with the variables to be interpolated in the sql query.
options | accepts `format`, `dp` and `jsonp`. This object also overrides the params passed to `$.ajax`.
##### Returns
A promise object. You can listen for the following events:
Events | Description
--- | ---
done | triggered when the data arrives.
error | triggered when something failed.
##### Example
You can also use done and error methods:
```javascript
sql.execute('SELECT * FROM table_name')
.done(fn)
.error(fnError)
```
### sql.getBounds(_sql [,vars][, options][, callback]_)
This query gets the bounding box for any dataset or filtered query using the CARTO.js library. The **getBounds** function is useful for guiding users to the right location on a map, or for loading the right data (at the right time), based on user actions.
Returns the bounds `[ [sw_lat, sw_lon], [ne_lat, ne_lon ] ]` for the geometry resulting of specified query.
##### Arguments
Name |Description
--- | ---
sql | a string with the sql query to calculate the bounds from.
##### Example
```javascript
sql.getBounds('select * from table').done(function(bounds) {
console.log(bounds);
});
```
#### getBounds and Leaflet
You can use the results from `getBounds` to center data on your maps using Leaflet.
```javascript
sql.getBounds('select * from table').done(function(bounds) {
map.setBounds(bounds);
// or map.fitBounds(bounds, mapView.getSize());
});
```

View File

@@ -0,0 +1,213 @@
## Static Maps
Static views of CARTO maps can be generated using the [Static Maps API](https://carto.com/docs/carto-engine/maps-api/static-maps-api/) within CARTO.js. The map's style, including the zoom and bounding box, follows from what was set in the `viz.json` file, but you can change the zoom, center, and size of your image with a few lines of code. You can also change your basemap Images can be placed in specified DOM elements on your page, or you can generate a URL for the image.
### Quick Start
The easiest way to generate an image is by using the following piece of code, which generates is replaced by an `img` tag once run in an HTML file:
```javascript
<script>
var vizjson_url = 'https://documentation.carto.com/api/v2/viz/008b3ec6-02c3-11e4-b687-0edbca4b5057/viz.json';
cartodb.Image(vizjson_url)
.size(600, 400)
.center([-3.4, 44.2])
.zoom(4)
.write({ class: "thumb", id: "AwesomeMap" });
</script>
```
##### Result
```html
<img id="AwesomeMap" src="https://cartocdn-ashbu.global.ssl.fastly.net/documentation/api/v1/map/static/center/04430594691ff84a3fdac56259e5180b:1419270587670/4/-3.4/44.2/600/400.png" class="thumb">
```
#### cartodb.Image(_layerSource[, options]_)
##### Arguments
Name |Description
--- | ---
layerSource | can be either a `viz.json` object or a [MapConfig object](https://carto.com/docs/carto-engine/maps-api/mapconfig#mapnik-layer-options).<br/><br/>**Note:** If defining an image through the MapConfig layer definition, you must set the `tiler_domain`, `tiler_port`, and `tiler_protocol`, as displayed in this [example](https://github.com/CartoDB/cartodb.js/blob/4ba5148638091fd2c194f48b2fa3ed6ac4ecdb23/examples/layer_definition.html). Otherwise the Static Image API tries to use your localhost to source the tiles and an error appears.
options |
--- | ---
&#124;_ basemap | change the basemap specified in the layer definition. Type: Object defining base map properties (see example below).
&#124;_ no_cdn | Disable CDN usage. Type: Boolean. Default: `false` (use CDN)
&#124;_ override_bbox | Override default of using the bounding box of the visualization. This is needed to use `Image.center` and `Image.zoom`. Type: Boolean. Default: `false` (use bounding box)
##### Returns
An `Image` object
##### Example
```javascript
<script>
var vizjson_url = 'https://documentation.carto.com/api/v2/viz/008b3ec6-02c3-11e4-b687-0edbca4b5057/viz.json';
var basemap = {
type: "http",
options: {
urlTemplate: "http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png",
subdomains: ["a", "b", "c"]
}
};
cartodb.Image(vizjson_url, {basemap: basemap})
.size(600, 400)
.center([0,0])
.write({ class: "thumb", id: "AwesomeMap" });
</script>
```
---
### cartodb.Image
#### Image.size(_width, height_)
Sets the size of the image.
##### Arguments
Name |Description
--- | ---
width | the width of the resulting image in pixels
height | the height of the resulting image in pixels
##### Returns
An `Image` object
#### Image.center(_latLng_)
Sets the center of the map.
##### Arguments
Name |Description
--- | ---
latLng | an array of the latitude and longitude of the center of the map. Example: `[40.4378271, -3.6795367]`
##### Returns
An `Image` object
#### Image.zoom(_zoomLevel_)
Sets the zoom level of the static map. Must be used with the option `override_bbox: true` if not using `Image.center` or `Image.bbox`.
##### Arguments
Name |Description
--- | ---
zoomLevel | the zoom of the resulting static map. `zoomLevel` must be an integer in the range [0,24].
##### Returns
An `Image` object
#### Image.bbox(_boundingBox_)
If you set `bbox`, `center` and `zoom` will be overridden.
##### Arguments
Name |Description
--- | ---
boundingBox | an array of coordinates making up the bounding box for your map. `boundingBox` takes the form: `[sw_lat, sw_lon, ne_lat, ne_lon]`.
##### Returns
An `Image` object
#### Image.into(_HTMLImageElement_)
Inserts the image into the HTML DOM element specified.
##### Arguments
Name |Description
--- | ---
HTMLImageElement | the DOM element where your image is to be located.
##### Returns
An `Image` object
##### Example
```javascript
cartodb.Image(vizjson_url).into(document.getElementById('map_preview'))
```
#### Image.write(_attributes_)
Adds an `img` tag in the same place script is executed. It's possible to specify a class name (`class`) and/or an id attribute (`id`) for the resulting image:
##### Arguments
Name |Description
--- | ---
class | the DOM class applied to the resulting `img` tag.
id | the DOM id applied to the resulting `img` tag.
src | path to a temporary image that acts as a placeholder while the static map is retrieved.
##### Returns
An `Image` object
##### Example
```javascript
<script>
cartodb.Image(vizjson_url)
.size(600, 400)
.center([-3.4, 44.2])
.zoom(10)
.write({ class: "thumb", id: "ImageHeader", src: 'spinner.gif' });
</script>
```
#### Image.getUrl(_callback(err, url)_)
Gets the URL for the image requested.
##### Callback Arguments
Name |Description
--- | ---
err | error associated with the image request, if any.
url | URL of the generated image.
##### Returns
An `Image` object
##### Example
```javascript
<script>
cartodb.Image(vizjson_url)
.size(600, 400)
.getUrl(function(err, url) {
console.log('image url',url);
})
</script>
```
#### Image.format(_format_)
Gets the URL for the image requested.
##### Arguments
Name |Description
--- | ---
format | image format of resulting image. One of `png` (default) or `jpg` (which have a quality of 85 dpi)
##### Returns
An `Image` object

View File

@@ -0,0 +1,77 @@
## Core API Functionality
In case you are not using Leaflet, or you want to implement your own layer object, CARTO provides a way to get the tiles url for a layer definition.
If you want to use this functionality, you only need to load cartodb.core.js from our cdn. No CSS is needed:
```html
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.core.js"></script>
```
An example using this functionality can be found in a ModestMaps example: [view live](http://cartodb.github.com/cartodb.js/examples/modestmaps.html) / [source code](https://github.com/CartoDB/cartodb.js/blob/develop/examples/modestmaps.html).
Notice that `cartodb.SQL` is also included in that JavaScript file
---
### cartodb.Tiles
#### cartodb.Tiles.getTiles(_layerOptions, callback_)
Fetch the tile template for the layer definition.
##### Arguments
Name |Description
--- | ---
layerOptions | the data that defines the layer. It should contain at least `user_name` and `sublayers` list.
options |
--- | ---
&#124;_ user_name |
&#124;_ sublayers |
&#124;_ maps_api_template |
callback(tilesUrl, error) | a function that recieves the tiles templates. In case of an error, the first param is null and the second one will be an object with an errors attribute that contains the list of errors.
##### Example
In this example, a layer with one sublayer is created. The sublayer renders all the content from a table.
```javascript
var layerData = {
user_name: 'username',
sublayers: [{
sql: "SELECT * FROM table_name";
cartocss: '#layer { marker-fill: #F0F0F0; }'
}],
maps_api_template: 'https://{username}.carto.com' // Optional
};
cartodb.Tiles.getTiles(layerData, function(tilesUrl, error) {
if (tilesUrl == null) {
console.log("error: ", error.errors.join('\n'));
return;
}
console.log("url template is ", tilesUrl.tiles[0]);
}
```
The `tilesUrl` object contains url template for tiles and interactivity grids:
```javascript
{
tiles: [
"http://{s}.carto.com/HASH/{z}/{x}/{y}.png",
...
],
grids: [
// for each sublayer there is one entry on this array
[
"http://{s}.carto.com/HASH/0/{z}/{x}/{y}.grid.json"
],
[
"http://{s}.carto.com/HASH/1/{z}/{x}/{y}.grid.json"
],
...
]
}
```

View File

@@ -0,0 +1,35 @@
## cartodb.js metrics
these are the metrics collected by cartodb.js. Can be printed in the browser opening a console and
executing
```
cartodb.core.Profiler.print_stats()
```
### layergroup stats
- **cartodb-js.layergroup.[type].time**: type can be get or post, depending on how the layergroup was fetch. It contains the time taken to fetch layergroup (including network time)
- **cartodb-js.layergroup.[type].error**: number of errors when fetching layergroup
**cartodb-js.layergroup.attributes.time**: time to fetch attributes (for example when an
infowindow is open)
**cartodb-js.layergroup.attributes.error**: fetching errors
**cartodb-js.named_map.attributes.time**: same than layergroup.attributes but for named maps
**cartodb-js.named_map.attributes.error**: fetching errors
### tiles stats
- **cartodb-js.tile.png.load.time**: time taken to load a *png* tile
- **cartodb-js.tile.png.error**: number of errors loading a png tile
### torque
- **torque.provider.windshaft.points**: number of points per tile
- **torque.provider.windshaft.process_time**: time used to process a tile. It does NOT include fetch
time
- **torque.provider.windshaft.tile.fetch**: time to fetch a torque tile
- **torque.provider.windshaft.tile.error**: failed tiles
- **torque.provider.windshaft.layergroup.time**: time to instanciate the map for torque tiles
- **torque.provider.windshaft.layergroup.error**:
- **torque.renderer.point.generateSprite**: time taken to generate a sprite based on css and point
properties
- **torque.renderer.point.renderLayers**: time to render all the layers for a tile
- **torque.renderer.point.renderTile**: time to render a tile

View File

@@ -0,0 +1,551 @@
This documentation is intended for developers and describes specific methods from the [latest version](https://github.com/CartoDB/cartodb.js/releases) 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 |
--- | ---
&#124;_ shareable | add facebook and twitter share buttons.
&#124;_ title | adds a header with the title of the visualization.
&#124;_ description | adds description to the header (as you set in the UI).
&#124;_ search | adds a search control (default: true).
&#124;_ zoomControl | adds zoom control (default: true).
&#124;_ loaderControl | adds loading control (default: true).
&#124;_ center_lat | latitude where the map is initializated.
&#124;_ center_lon | longitude where the map is initializated.
&#124;_ zoom | initial zoom.
&#124;_ cartodb_logo | default to true, set to false if you want to remove the CARTO logo.
&#124;_ infowindow | set to false if you want to disable the infowindow (enabled by default).
&#124;_ 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](http://bl.ocks.org/michellechandra/081ca7160a8c782266d2) for an example.<br/><br/> For details about customizing the time slider, see the [Torque.js](https://carto.com/docs/carto-engine/torque/torque-time-slider/) documentation.
&#124;_ layer_selector | show layer selector (default: false).
&#124;_ legends | if it's true legends are shown in the map.
&#124;_ 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.
&#124;_ scrollwheel | enable/disable the ability of zooming using scrollwheel (default enabled)
&#124;_ fullscreen | if true adds a button to toggle the map fullscreen
&#124;_ mobile_layout | if true enables a custom layout for mobile devices (default: false)
&#124;_ force_mobile | forces enabling/disabling the mobile layout (it has priority over mobile_layout argument)
&#124;_ 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'.
&#124;_ gmaps_style | Google Maps styled maps. See [documentation](https://developers.google.com/maps/documentation/javascript/styling).
&#124;_ 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
```javascript
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)<br /><br /> - 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](https://carto.com/docs/carto-engine/carto-js/ui-functions/).
#### Returns
An overlay object, see [vis.Overlays](#visoverlays).
#### 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.
{% highlight html %}
layer.leafletMap.viz.addOverlay({
type: 'tooltip',
layer: sublayer,
template: '<div class="cartodb-tooltip-content-wrapper"><img style="width: 100%" src={{_url}}>{{name}}, {{age}}, {{city}}, {{country}}</div>',
position: 'bottom|right',
fields: [{ name: 'name' }]
});
{% endhighlight %}
**Tip:** For a description of the infowindow specific parameters, see [`cartodb.vis.Vis.addInfowindow(_map, layer, fields [, options]_)`](https://carto.com/docs/carto-engine/carto-js/ui-functions/#cartodbvisvisaddinfowindowmap-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
```javascript
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](http://backbonejs.org/#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<br/><br/>**Tip:** See [Multiple types of layers Source Object](http://docs.carto.com/carto-engine/carto-js/layer-source-object/#multiple-types-of-layers-source-object)
options |
--- | ---
&#124;_ https | loads the layer as HTTPS. True forces the layer to load. See [HTTPS support](https://carto.com/docs/carto-engine/carto-js/getting-started/#https-support) for example code.
&#124;_ refreshTime | if set, the layer is auto refreshed in milliseconds. See a refreshTime code [example](https://github.com/CartoDB/cartodb.js/blob/develop/examples/createLayer_refresh_time.html).<br/><br/>**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`).
&#124;_ infowindow | set to false if you want to disable the infowindow (enabled by default). For details, see [Creating an infowindow with the `createLayer()` function](http://docs.carto.com/faqs/infowindows/#creating-an-infowindow-with-the-createlayer-function).
&#124;_ 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)](http://docs.carto.com/carto-editor/maps/#infowindows) option. This option disables the tooltip in createLayer.<br/><br/>See a tooltip code [example](https://github.com/CartoDB/cartodb.js/blob/develop/examples/createLayer_custom_tooltip.html).
&#124;_ legends | set to true to show legends in the map. For an example, see this [CARTO.js example with legends disabled](https://github.com/CartoDB/cartodb.js/blob/develop/examples/createLayer_noLegend.html).
&#124;_ 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](https://github.com/CartoDB/cartodb.js/blob/develop/examples/torque_time_slider.html).<br/><br/> For details about customizing the time slider, see the [Torque.js](http://docs.carto.com/carto-engine/torque/torque-time-slider/) documentation.
&#124;_ 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](http://docs.carto.com/carto-engine/torque-js/) documentation.
&#124;_ 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).<br/><br/>See [`layer.featureOver(_event, latlng, pos, data, layerIndex_`)](http://docs.carto.com/carto-engine/carto-js/events/#layerfeatureoverevent-latlng-pos-data-layerindex) for details about binding functions to layer events.
&#124;_ 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')](http://docs.carto.com/carto-engine/maps-api/mapconfig/#layergroup-configurations). All non-torque layers (http and mapnik) will be rendered if this option is not present.<br/><br/>See a createLayer filter [example](http://docs.carto.com/carto-engine/carto-js/layer-source-object/#multiple-types-of-layers-source-object).
&#124;_ no_cdn | set to true to disable CDN when fetching tiles. For a complete example of this code, see ["odyssey_test.html"](https://github.com/CartoDB/cartodb.js/blob/2983b2fdcef914afdb1f4fdae173471143930452/examples/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.<br/><br/> See the [example of loading multiple layers from CARTO in a Leaflet Map](https://github.com/CartoDB/cartodb.js/blob/develop/examples/callback_layer.html).
### Passing the url where the layer data is located
```javascript
cartodb.createLayer(map, 'http://myserver.com/layerdata.json')
```
### Passing the data directly
```javascript
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
```javascript
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](http://docs.carto.com/carto-engine/carto-js/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
```javascript
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`
```javascript
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
```javascript
{
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](http://www.postgresql.org/docs/9.3/interactive/sql-syntax.html) and [CartoCSS](http://docs.carto.com/carto-engine/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
```javascript
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](https://carto.com/docs/carto-engine/maps-api/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](https://carto.com/docs/carto-engine/maps-api/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
```javascript
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
```javascript
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`](#cartodbsublayerbase)._
### 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](https://carto.com/docs/carto-engine/carto-js/ui-functions/#cartodbvisvisaddinfowindowmap-layer-fields--options).
#### Attributes
Name | Description
--- | ---
template | Custom HTML template for the infowindow. You can write simple HTML or use [Mustache templates](http://mustache.github.com/).
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](https://github.com/CartoDB/cartodb.js/tree/develop/themes/css/infowindow) for the latest stylesheet code.
#### Example
```html
<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>{{content.data.name}}</h4>
</div>
</div>
<div class="cartodb-popup-tip-container"></div>
</div>
</script>
```
[Here is the complete example source code](https://github.com/CartoDB/cartodb.js/blob/develop/examples/custom_infowindow.html)
---
## cartodb.HttpSubLayer
_This is a subclass of [`cartodb.SubLayerBase`](#cartodbsublayerbase)._
### 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.

View File

@@ -0,0 +1,219 @@
## Vizjson
This is the spec for visjson:
```
{
// 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
}
}],
}
```

View File

@@ -0,0 +1,35 @@
## Versions
Be mindful of the CARTO.js version that you are using for development. For any live code, it is recommended to link directly to the tested CARTO.js version from your development environment. You can check the version of CARTO.js as follows:
### cartodb.VERSION
Returns the version of the library. It should be something such as, `3.0.1`.
### Persistent Version Hosting
CARTO is committed to making sure your website works as intended, no matter what changes in the future. As time progresses, it is expected that we will find more efficient, and useful, features to add to the library. Since we never want to break things that you have already developed, we provide versioned CARTO.js libraries. Regardless of the version, the library functionality will never unexpectedly change on you.
**Note:** It is recommended to always develop against the most recent version of CARTO.js:
```html
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
```
Anytime you wish to push a stable version of your site to the web, you can find the version of CARTO.js that you are using located in the first line of the library, or by running the following in your code:
```javascript
alert(cartodb.VERSION)
```
Once you know which version of CARTO.js you are using, you can point your site to that release. For example, if the current version of CARTO.js is 3.15.8, the URL would be:
```html
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15.8/cartodb.js"></script>
```
You can do the same for the CSS documents we provide:
```html
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15.8/themes/css/cartodb.css" />
```

View File

@@ -0,0 +1,13 @@
## Support Options
*CartoDB.js v3.15* is **no longer being actively developed**. Major bugs will be addressed as needed.
You can check out the new release of *CARTO.js v4* in the [documentation](https://carto.com/developers/carto-js/) and its [support options](https://carto.com/developers/carto-js/support/support-options/).
However, if you feel stuck, there are many ways to find help.
* Ask a question on [GIS StackExchange](https://gis.stackexchange.com/questions/tagged/carto) using the `CARTO` tag.
* [Report an issue](https://github.com/CartoDB/carto.js/issues) in Github.
* Enterprise Plan customers have additional access to enterprise-level support through CARTO's support representatives.
If you just want to describe an issue or share an idea, just <a class="typeform-share" href="https://cartohq.typeform.com/to/mH6RRl" data-mode="popup" target="blank"> send your feedback</a><script>(function() { var qs,js,q,s,d=document, gi=d.getElementById, ce=d.createElement, gt=d.getElementsByTagName, id="typef_orm_share", b="https://embed.typeform.com/"; if(!gi.call(d,id)){ js=ce.call(d,"script"); js.id=id; js.src=b+"embed.js"; q=gt.call(d,"script")[0]; q.parentNode.insertBefore(js,q) } })() </script>.

View File

@@ -0,0 +1,5 @@
## Contribute
*CartoDB.js v3.15* is **no longer being actively developed**. Major bugs will be addressed as needed.
You can check out the new release of *CARTO.js v4* in the [documentation](https://carto.com/developers/carto-js/) and how to [contribute](https://carto.com/developers/carto-js/support/contribute/).