cdb
This commit is contained in:
@@ -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');
|
||||
```
|
||||
|
||||
That’s 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)).
|
||||
@@ -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:
|
||||
--- | ---
|
||||
|_ `mapnik`| See [Mapnik Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#mapnik-layer-options).
|
||||
|_ `cartodb` | An alias for Mapnik (for backward compatibility).
|
||||
|_ `torque` | See [Torque Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#torque-layer-options).
|
||||
|_ `http` | See [HTTP Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#http-layer-options).
|
||||
|_ `plain` | See [Plain Layer Options](http://docs.carto.com/carto-engine/maps-api/mapconfig/#plain-layer-options).
|
||||
|_ `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'] })
|
||||
```
|
||||
@@ -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.
|
||||
@@ -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 |
|
||||
--- | ---
|
||||
|_ infowindowTemplate | allows you to set the HTML of the template.
|
||||
|_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 %}
|
||||
@@ -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**. It’s 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());
|
||||
});
|
||||
```
|
||||
@@ -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 |
|
||||
--- | ---
|
||||
|_ basemap | change the basemap specified in the layer definition. Type: Object defining base map properties (see example below).
|
||||
|_ no_cdn | Disable CDN usage. Type: Boolean. Default: `false` (use CDN)
|
||||
|_ 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
|
||||
@@ -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 |
|
||||
--- | ---
|
||||
|_ user_name |
|
||||
|_ sublayers |
|
||||
|_ 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"
|
||||
],
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user