Merge pull request #248 from CartoDB/newdocs

split files
This commit is contained in:
Carlos Matallín 2016-01-19 11:00:27 +01:00
commit 33396b4871
3 changed files with 264 additions and 157 deletions

View File

@ -1,161 +1,8 @@
# Torque API
Torque.js is an efficient and stylish rendering method to animate your data. Torque.js uses [TileCubes](http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification), which are JSON representations of multidimensional data with geospatial coordinates, to render data on the client.
## L.TorqueLayer(options)
One of two core classes for the Torque library - it is used to create an animated torque layer with custom settings.
### Usage example
```js
// initialize a torque layer that uses the CartoDB account details and SQL API to pull in data
var torqueLayer = new L.TorqueLayer({
user : 'viz2',
table : 'ow',
cartocss: CARTOCSS
});
```
### Options
##### Provider options
| Option | type | Default | Description | Options |
|-----------|:-----------|:----------|:---------------------------------------|---------|
| provider | string | ```sql_api``` | Where is the data coming from | `sql_api`, `url_template`, or `windshaft` |
##### CartoDB data options (SQL API provider)
| Option | type | Default | Description |
|-----------|:-----------|:----------|:---------------------------------------|
| user_name | string | ```null``` | CartoDB account name. Found from: http://accountname.cartodb.com|
| table_name | string | ```null``` | CartoDB table name where data is found |
| query | string | ```null``` | SQL query to be performed to fetch the data. You must use this param or table, not at the same time |
| cartocss | string | ```null``` | CartoCSS style for this map |
| loop | boolean | ```true``` | If ```false```, the animation is paused when it reaches the last frame |
### Time methods
| Method | options | returns | Description |
|-----------|:-----------|:----------|:---------------------------------------|
| ```setStep(step)``` | ```time numeric``` | ```this``` | sets the animation to the step indicated by ```step```, must be between 0 and ```steps```|
| ```play()```| | ```this```| starts the animation
| ```stop()```| | ```this```| stops the animation and set time to step 0
| ```pause()```| | ```this```| stops the animation but keep the current time (play enables the animation again)
| ```toggle()```| | ```this```| toggles (pause/play) the animation
| ```getStep()``` | | current animation step (integer) | gets the current animation step
| ```getTime()``` | | current animation time (Date) | gets the real animation time
| ```isRunning()``` | | `true`/`false` | describes whether the Torque layer is playing or is stopped
### Layer control methods
| Method | options | returns | Description |
|-----------|:-----------|:----------|:---------------------------------------|
| ```hide()``` | none |```this``` | hides the Torque layer |
| ```show()```| none| ```this``` | shows the Torque layer |
### Style methods
| Method | options | returns | Description |
|-----------|:-----------|:----------|:---------------------------------------|
| ```setCartoCSS(cartocss)``` | ```cartocss string``` | ```this``` | style the map rendering using client-side cartocss (not available with named maps) |
The full CartoCSS spec is not supported by Torque but instead only a limited subset with some additions related to torque rendering. To see the full list of supported parameters, read the [Torque CartoCSS documentation](CartoCSS.md). ``value`` and ``zoom`` variables can be used. ``value`` is the value of aggregation (see ``countby`` constructor option). ``zoom`` is the current zoom being rendered
TorqueLayer currently expects ```marker``` styling.
##### CartoCSS Example
This should be ```string``` encoded in Javascript.
```css
#layer {
marker-fill: #662506;
marker-width: 20;
[value > 1] { marker-fill: #FEE391; }
[value > 2] { marker-fill: #FEC44F; }
[value > 3] { marker-fill: #FE9929; }
[value > 4] { marker-fill: #EC7014; }
[value > 5] { marker-fill: #CC4C02; }
[value > 6] { marker-fill: #993404; }
[value > 7] { marker-fill: #662506; }
[frame-offset = 1] { marker-width: 20; marker-fill-opacity: 0.05;}' // renders the previous frame
[frame-offset = 2] { marker-fill: red; marker-width: 30; marker-fill-opacity: 0.02;}' // renders two frames ago from the current being rendered
}
```
### Data methods
| Method | options | returns | Description |
|-----------|:-----------|:----------|:---------------------------------------|
| ```setSQL(sql statement)``` | ```SQL string``` | ```this``` | Change the SQL on the data table (not available with named maps) |
| ```error(callback)``` | ```callback function with a list of errors as argument``` | ```this``` | specifies a callback function to run if there are query errors |
##### SQL Example
Limit the data used in the Torque map.
```js
torqueLayer.setSQL("SELECT * FROM table LIMIT 100");
```
### Interaction methods (only available for Leaflet)
| Method | options | returns | Description |
|-----------|:-----------|:----------|:---------------------------------------|
| ```getValueForPos(x, y[, step])```| | an object like { bbox:[], value: VALUE } if there is value for the pos, null otherwise | allows to get the value for the coordinate (in map reference system) for a concrete step. If step is not specified the animation one is used. This method is expensive in terms of CPU so be careful. It returns the value from the raster data not the rendered data |
| ```getValueForBBox(xstart, ystart, xend, yend)```| | a number | returns an accumulated numerical value from all the torque areas within the specified bounds |
| ```getActivePointsBBox(step)```| | list of bbox | returns the list of bounding boxes active for ``step``
| ```getValues(step)```| | list of values| returns the list of values for the pixels active in ``step``
| ```invalidate()```| | | forces a reload of the layer data.
### Interaction methods (only available for Leaflet)
| Method | options | returns | Description |
|-----------|:-----------|:----------|:---------------------------------------|
| ```getActivePointsBBox(step)```| | list of bbox | returns the list of bounding boxes active for ``step``
| ```invalidate()```| | | forces a reload of the layer data.
### Events
Events in Torque follow the format:
```js
torqueLayer.on('event-type', function([callback_obj]) {
// do something
});
```
| Events | callback object | Description |
|-----------|:----------|:---------------------------------------|
| ```change:steps```| current step | When a map changes steps, this event is triggered |
| ```change:time```| current time, step number | When a map changes time, this event is triggered |
| ```play```| none | Triggered when the Torque layer is played |
| ```pause```| none | Triggered when the Torque layer is paused |
| ```stop```| none | Triggered when the Torque layer is stopped |
| ```load```| none | Triggered when the Torque layer is loaded |
##### Event Example
Print the current step to the console log.
```js
torqueLayer.on('change:steps', function(step) {
// do something with step
console.log("Current step is " + step);
});
```
# Google Maps Layers
## GMapsTorqueLayer(options)
This class does exactly the same as ``L.TorqueLayer`` but using Google Maps instead. The main difference is that this class
is not a layer but is an overlay, so in order to add it to the a map use, ``layer.setMap`` instead of ``overlayMapTypes``. See the [Overlay View](https://developers.google.com/maps/documentation/javascript/reference#OverlayView) reference in Google Maps API doc.
### Options
##### options
| Option | type | Default | Description |
|-----------|:-----------|:----------|:---------------------------------------|
| map | google.maps.Map | | google.maps.Map instance |
see ``L.TorqueLayer`` for the rest of the options.
## Documentation
* [Getting Started with Torque.js](getting_started.md)
* [Torque API Methods](torque_api.md)

93
doc/getting_started.md Normal file
View File

@ -0,0 +1,93 @@
##Getting Started
Although the most straightforward way to use Torque is through either the CartoDB Editor, or by passing the layer's viz.json to [CartoDB.js](http://docs.cartodb.com/cartodb-platform/cartodb-js/getting-started/), many use cases work best with the standalone [Torque.js](https://github.com/CartoDB/torque/tree/master/dist). Assuming you have a public dataset with a `date` column, it is really simple to create an animated map with the library. First, you need to have a Leaflet map prepared in an HTML page:
```html
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<body>
<div id="map"></div>
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<script>
var map = new L.Map('map', {
zoomControl: true,
center: [40, 0],
zoom: 3
});
L.tileLayer('http://{s}.api.cartocdn.com/base-dark/{z}/{x}/{y}.png', {
attribution: 'CartoDB'
}).addTo(map);
</script>
</body>
```
For Torque to work with your table, you only need a username, the name of the table, and a CartoCSS string to style the map. Leaflet's method `addTo` adds the Torque layer to the map. `play` runs the animation with the options specified in the CartoCSS properties.
```html
<script>
var CARTOCSS = [
'Map {',
'-torque-time-attribute: "date";',
'-torque-aggregation-function: "count(cartodb_id)";',
'-torque-frame-count: 760;',
'-torque-animation-duration: 15;',
'-torque-resolution: 2',
'}',
'#layer {',
' marker-width: 3;',
' marker-fill-opacity: 0.8;',
' marker-fill: #FEE391; ',
' comp-op: "lighten";',
'}'
].join('\n');
var torqueLayer = new L.TorqueLayer({
user : 'your_username',
table : 'your_table_name',
cartocss: CARTOCSS
});
torqueLayer.addTo(map);
torqueLayer.play()
</script>
```
You can use any kind of tile source outside CartoDB, by specifying the location of a [valid TileJSON](https://github.com/mapbox/tilejson-spec) file:
```javascript
var torqueLayer = new L.TorqueLayer({
tileJSON: 'http://url.to/tile.json'
cartocss: CARTOCSS
});
```
Optionally, it is also possible to use a custom SQL query for your visualization:
```javascript
var torqueLayer = new L.TorqueLayer({
user : 'your_username',
table : 'your_table_name',
sql_query : 'SELECT * FROM your_table_name WHERE whatever'
cartocss: CARTOCSS
});
```
Like in a video player, you can use animation control methods such as `play`, `stop` and `pause` at any point. Torque's animator fires a `change:time` event each time the animation "ticks" to the next frame, and there are a number of properties and methods that can be run during playback, which are detailed in the [API documentation](/cartodb-platform/torque/torqueapi/). At any point, for example, the styling of the layer's markers can be changed using the `layer.setCartoCSS('##style##')`.
##Usage Examples
The best way to start learning about the library is by taking a look at some of the examples below:
* A basic example using the WWI British Navy dataset - ([view live](http://cartodb.github.io/torque/examples/navy_leaflet.html) / [source code](https://github.com/CartoDB/torque/blob/master/examples/navy_leaflet.html))
* Using tileJSON to fetch tiles - ([view live](http://cartodb.github.io/torque/examples/tilejson.html) / [source code](https://github.com/CartoDB/torque/blob/master/examples/tilejson.html))
* A car's route at the Nürburgring track mapped in Torque - ([view live](http://cartodb.github.io/torque/examples/car.html) / [source code](https://github.com/CartoDB/torque/blob/master/examples/car.html))
## Additional Torque Resources
The following links contain examples, and other public information, about using Torque maps.
- Torque [CartoCSS Reference page](https://github.com/cartodb/torque-reference), useful for building parsers, tests, compilers, and syntax highlighting/checking
- CartoDB repository of [examples](https://github.com/CartoDB/torque/tree/master/examples)
- A CartoDB [time example](http://cartodb.github.com/torque/) of a Torque map and data
- CartoDB wiki page describing [how spatial aggregration works](https://github.com/CartoDB/torque/wiki/How-spatial-aggregation-works)
- The [Guardian's Data Blog](http://www.guardian.co.uk/news/datablog/interactive/2012/oct/01/first-world-war-royal-navy-ships-mapped) about Royal Navy ships in WWI using a Torque map
- An example of how to create a [simple Torque visualization](https://github.com/CartoDB/torque#getting-started) and the [source code](https://github.com/CartoDB/torque/blob/master/examples/navy_leaflet.html) used to create the example
- An example of how to use CartoDB.js to [add a Torque layer from a named map with auth_tokens enabled](https://gist.github.com/chriswhong/a4d1e6305ecaf2ad507a)

167
doc/torque_api.md Normal file
View File

@ -0,0 +1,167 @@
# Torque API
### L.TorqueLayer(options)
A layer to be added to a Leaflet map. It works as a regular tiled layer within the Leaflet tile pane, but instead of containing `<img>` elements, it's composed of a single [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) where all markers are drawn.
```javascript
var torqueLayer = new L.TorqueLayer({
user: 'viz2',
table: 'ow',
cartocss: '<cartocss here>'
});
map.addLayer(torqueLayer);
```
#### Options
Name | Description
--- | ---
cartocss | A string object, the CartoCSS style for the map. Default value is ```null```
loop | A boolean object that defines the animation loop. Default value is ```true```. If ```false```, the animation is paused when it reaches the last frame
resolution | Spatial resolution in pixels. A resolution of 1 means no spatial aggregation of the data. Its value must be a power of 2
steps | Number of steps that the animation is divided into
animationDuration | Duration, in seconds, of the animation
zIndex | Z-Index CSS property of the layer
attribution | Attribution to be added in the bottom right of the map
maxZoom | Maximum zoom for the layer.
tileSize | Size, in pixels of the tiles
##### Using a CartoDB table directly
Name | Description
--- | ---
user | A string object, your CartoDB [account name](/cartodb-editor/your-account/#account). Default value is ```null```
table | A string object, the CartoDB table name where data is found (also known as a dataset.) Default value is ```null```
##### Using a custom SQL query
Name | Description
--- | ---
query | A string object, the SQL query to be performed to fetch the data. Default value is ```null```.<br/><br/>You must use this param or table, but not at the same time
**Tip:** For a Torque category layer that is created dynamically with `cartodb.createLayer`, the SQL query must explicitly include how to build the torque_category column. You must include both the `sql` and `table_name` parameters. See this [createLayer with torque category layer](https://gist.github.com/danicarrion/dcaf6f00a71aa55134b4) example.
##### Providing a TileJSON file
Name | Description
--- | ---
tileJSON | A URL pointing to a valid [TileJSON](https://github.com/mapbox/tilejson-spec) file from which to get the Torque tile templates
#### Time Methods
Method | Options | Returns | Description |
---|---|---|---|
`setStep(step)` | `time numeric` | `this` | the value must be between 0 and the total number of `steps` in the animation
`play()` | | `this` | starts the animation
`stop()` | | `this` | stops the animation and set time to step 0
`pause()` | | `this` | stops the animation but keep the current time (play enables the animation again)
`toggle()` | | `this` | toggles (pause/play) the animation
`getStep()` | | current animation step (integer) | gets the current animation step. A step is considered an animation frame
`getTime()` | | current animation time (Date) | gets the real animation time
`isRunning()` | | `true`/`false` | describes whether the Torque layer is playing or is stopped
**Note:** Torque.js interprets the beginning and ending date/time from your "Time Column" as one block, then divides that up into [Steps](/cartodb-platform/cartocss/properties-for-torque/#torque-frame-count-number), depending on the number you set. It does not necessarily draw one frame for each row.
#### Layer Control Methods
Method | Options | Returns | Description
---|---|---|---
`hide()` | none | `this` | hides the Torque layer
`show()` | none| `this` | shows the Torque layer
#### Style Methods
Method | Options | Returns | Description
---|---|---|---|
`setCartoCSS(cartocss)` | `cartocss string` | `this` | style the map rendering using client-side CartoCSS (not available with [Named maps](/cartodb-platform/maps-api/named-maps/))
Torque supports a limited subset of CartoCSS rules defined in the [torque-reference](https://github.com/cartodb/torque-reference). To see the full list of supported rules, read the [Torque CartoCSS documentation](/cartodb-platform/cartocss/properties-for-torque/). `value` and `zoom` variables can be used. `value` is the value of aggregation. `zoom` is the current zoom being rendered.
TorqueLayer currently expects `marker` styling.
#### Example
This is how a minimal example of a stylesheet for a Torque visualisation would look like.
```css
Map {
-torque-time-attribute: "date";
-torque-aggregation-function: "count(cartodb_id)";
-torque-frame-count: 760;
-torque-animation-duration: 15;
-torque-resolution: 2;
}
#layer {
marker-width: 3;
marker-fill-opacity: 0.8;
marker-fill: #FEE391;
}
#layer[value = 4] { // Use of the value variable, generated by the function specified in -torque-aggregation-function
marker-fill: #FABADA;
}
#layer[zoom = 12] { // Use of the zoom variable
marker-width: 10;
}
```
### Data Methods
Method | Options | Returns | Description
---|---|---|---
`setSQL(sql statement)` | `SQL string` | `this` | Change the SQL on the data table (not available with named maps)
`error(callback)` | `callback function with a list of errors as argument` | `this` | specifies a callback function to run if there are query errors
#### Example
SQL Example to limit the data used in the Torque map.
```js
torqueLayer.setSQL("SELECT * FROM table LIMIT 100");
```
### Events
_**Note:** You can only run events after the [required libraries](/cartodb-platform/torque/torquejs-getting-started/#advanced-torquejs-libraries) are loaded. Otherwise, the [interaction methods](/cartodb-platform/torque/torque-interaction-methods/) will not work._
Events in Torque follow the format:
```js
torqueLayer.on('event-type', function([callback_obj]) {
// do something
});
```
Events | Callback Object | Description
---|---|---
`change:steps` | current step | When a map changes steps, this event is triggered
`change:time` | current time, step number | When a map changes time, this event is triggered
`play` | none | Triggered when the Torque layer is played
`pause` | none | Triggered when the Torque layer is paused
`stop` | none | Triggered when the Torque layer is stopped
`load` | none | Triggered when the Torque layer is loaded
#### Example
An event example to print the current step to the console log.
```js
torqueLayer.on('change:steps', function(step) {
// do something with step
console.log('Current step is ' + step);
});
```
## Google Maps Layers
### GMapsTorqueLayer(_options_)
This class does exactly the same as ``L.TorqueLayer`` but using Google Maps instead. The main difference is that this class
is not a layer but is an overlay, so in order to add it to the a map use, ``layer.setMap`` instead of ``overlayMapTypes``. See the [Overlay View](https://developers.google.com/maps/documentation/javascript/reference#OverlayView) reference in Google Maps API doc.
#### Options
Name | Description
--- | ---
map | A google.maps.Map instance