From 8db1ad6f1912def4bfe68c02686b71580309c0d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Thu, 22 Oct 2015 13:28:08 +0200 Subject: [PATCH 01/33] newdocs: split files --- docs/Map-API.md | 980 +-------------------------------------- docs/anonymous_maps.md | 200 ++++++++ docs/general_concepts.md | 27 ++ docs/named_maps.md | 424 +++++++++++++++++ docs/quickstart.md | 105 +++++ docs/static_maps_api.md | 212 +++++++++ 6 files changed, 975 insertions(+), 973 deletions(-) create mode 100644 docs/anonymous_maps.md create mode 100644 docs/general_concepts.md create mode 100644 docs/named_maps.md create mode 100644 docs/quickstart.md create mode 100644 docs/static_maps_api.md diff --git a/docs/Map-API.md b/docs/Map-API.md index 75f20301..a93af594 100644 --- a/docs/Map-API.md +++ b/docs/Map-API.md @@ -1,977 +1,11 @@ -## Maps API +# Maps API The CartoDB Maps API allows you to generate maps based on data hosted in your CartoDB account and you can apply custom SQL and CartoCSS to the data. The API generates a XYZ-based URL to fetch Web Mercator projected tiles using web clients such as [Leaflet](http://leafletjs.com), [Google Maps](https://developers.google.com/maps/), or [OpenLayers](http://openlayers.org/). -You can create two types of maps with the Maps API: +## Documentation -- **Anonymous maps** - You can create maps using your CartoDB public data. Any client can change the read-only SQL and CartoCSS parameters that generate the map tiles. These maps can be created from a JavaScript application alone and no authenticated calls are needed. See [this CartoDB.js example]({{ '/cartodb-platform/cartodb-js.html' | prepend: site.baseurl }}). - -- **Named maps** - There are also maps that have access to your private data. These maps require an owner to setup and modify any SQL and CartoCSS parameters and are not modifiable without new setup calls. - -## Quickstart - -### Anonymous maps - -Here is an example of how to create an anonymous map with JavaScript: - -```javascript -var mapconfig = { - "version": "1.3.1", - "layers": [{ - "type": "cartodb", - "options": { - "cartocss_version": "2.1.1", - "cartocss": "#layer { polygon-fill: #FFF; }", - "sql": "select * from european_countries_e" - } - }] -} - -$.ajax({ - crossOrigin: true, - type: 'POST', - dataType: 'json', - contentType: 'application/json', - url: 'https://documentation.cartodb.com/api/v1/map', - data: JSON.stringify(mapconfig), - success: function(data) { - var templateUrl = 'https://documentation.cartodb.com/api/v1/map/' + data.layergroupid + '/{z}/{x}/{y}.png' - console.log(templateUrl); - } -}) -``` - -### Named maps - -Let's create a named map using some private tables in a CartoDB account. -The following map config sets up a map of European countries that have a white fill color: - -```javascript -{ - "version": "0.0.1", - "name": "test", - "auth": { - "method": "open" - }, - "layergroup": { - "layers": [{ - "type": "mapnik", - "options": { - "cartocss_version": "2.1.1", - "cartocss": "#layer { polygon-fill: #FFF; }", - "sql": "select * from european_countries_e" - } - }] - } -} -``` - -The map config needs to be sent to CartoDB's Map API using an authenticated call. Here we will use a command line tool called `curl`. For more info about this tool, see [this blog post](http://quickleft.com/blog/command-line-tutorials-curl), or type ``man curl`` in bash. Using `curl`, and storing the config from above in a file `mapconfig.json`, the call would look like: - -
-```bash -curl 'https://{account}.cartodb.com/api/v1/map/named?api_key=APIKEY' -H 'Content-Type: application/json' -d @mapconfig.json -``` - -To get the `URL` to fetch the tiles you need to instantiate the map, where `template_id` is the template name from the previous response. - -
-```bash -curl -X POST 'https://{account}.cartodb.com/api/v1/map/named/:template_id' -H 'Content-Type: application/json' -``` - -The response will return JSON with properties for the `layergroupid`, the timestamp (`last_updated`) of the last data modification and some key/value pairs with `metadata` for the `layers`. -Note: all `layers` in `metadata` will always have a `type` string and a `meta` dictionary with the key/value pairs. - -Here is an example response: - -```javascript -{ - "layergroupid": "c01a54877c62831bb51720263f91fb33:0", - "last_updated": "1970-01-01T00:00:00.000Z", - "metadata": { - "layers": [ - { - "type": "mapnik", - "meta": {} - } - ] - } -} -``` - -You can use the `layergroupid` to instantiate a URL template for accessing tiles on the client. Here we use the `layergroupid` from the example response above in this URL template: - -```bash -https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/{z}/{x}/{y}.png -``` - -## General Concepts - -The following concepts are the same for every endpoint in the API except when it's noted explicitly. - -### Auth - -By default, users do not have access to private tables in CartoDB. In order to instantiate a map from private table data an API Key is required. Additionally, to include some endpoints, an API Key must be included (e.g. creating a named map). - -To execute an authorized request, `api_key=YOURAPIKEY` should be added to the request URL. The param can be also passed as POST param. Using HTTPS is mandatory when you are performing requests that include your `api_key`. - -### Errors - -Errors are reported using standard HTTP codes and extended information encoded in JSON with this format: - -```javascript -{ - "errors": [ - "access forbidden to table TABLE" - ] -} -``` - -If you use JSONP, the 200 HTTP code is always returned so the JavaScript client can receive errors from the JSON object. - -### CORS support - -All the endpoints, which might be accessed using a web browser, add CORS headers and allow OPTIONS method. - -## Anonymous Maps - -Anonymous maps allows you to instantiate a map given SQL and CartoCSS. It also allows you to add interaction capabilities using [UTF Grid.](https://github.com/mapbox/utfgrid-spec) - -### Instantiate - -#### Definition - -
-```html -POST /api/v1/map -``` - -#### Params - -```javascript -{ - "version": "1.3.0", - "layers": [{ - "type": "mapnik", - "options": { - "cartocss_version": "2.1.1", - "cartocss": "#layer { polygon-fill: #FFF; }", - "sql": "select * from european_countries_e", - "interactivity": ["cartodb_id", "iso3"] - } - }] -} -``` - -Should be a [Mapconfig](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md). - -#### Response - -The response includes: - -- **layergroupid** - The ID for that map, used to compose the URL for the tiles. The final URL is: - - ```html - https://{account}.cartodb.com/api/v1/map/:layergroupid/{z}/{x}/{y}.png - ``` - -- **updated_at** - The ISO date of the last time the data involved in the query was updated. - -- **metadata** - Includes information about the layers. - - - -- **cdn_url** - URLs to fetch the data using the best CDN for your zone. - -#### Example - -
REQUEST
-```bash -curl 'https://documentation.cartodb.com/api/v1/map' -H 'Content-Type: application/json' -d @mapconfig.json -``` - -
RESPONSE
-```javascript -{ - "layergroupid": "c01a54877c62831bb51720263f91fb33:0", - "last_updated": "1970-01-01T00:00:00.000Z", - "metadata": { - "layers": [ - { - "type": "mapnik", - "meta": {} - } - ] - }, - "cdn_url": { - "http": "http://cdb.com", - "https": "https://cdb.com" - } -} -``` - -##### Retrieve resources from the layergroup - -###### Mapnik tiles can be accessed using: - -These tiles will get just the mapnik layers. To get individual layers see next section. - -```bash -https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/{z}/{x}/{y}.png -``` - -###### Individual layers - -The MapConfig specification holds the layers definition in a 0-based index. Layers can be requested individually in different formats depending on the layer type. - -Individual layers can be accessed using that 0-based index. For UTF grid tiles: - -```bash -https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer/{z}/{x}/{y}.grid.json -``` - -In this case, `:layer` as 0 returns the UTF grid tiles/attributes for layer 0, the only layer in the example MapConfig. - -If the MapConfig had a Torque layer at index 1 it could be possible to request it with: - -```bash -https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/1/{z}/{x}/{y}.torque.json -``` - -###### Attributes defined in `attributes` section: - -```bash -https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer/attributes/:feature_id -``` - -Which returns JSON with the attributes defined, like: - -```javascript -{ "c": 1, "d": 2 } -``` - -###### Blending and layer selection - -```bash -https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer_filter/{z}/{x}/{y}.png -``` - -Note: currently format is limited to `png`. - -`:layer_filter` can be used to select some layers to be rendered together. `:layer_filter` supports two formats: - -- `all` alias - -Using `all` as `:layer_filter` will blend all layers in the layergroup - -```bash -https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/all/{z}/{x}/{y}.png -``` - -- Filter by layer index - -A list of comma separated layer indexes can be used to just render a subset of layers. For example `0,3,4` will filter and blend layers with indexes 0, 3, and 4. - -```bash -https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/0,3,4/{z}/{x}/{y}.png -``` - -Some notes about filtering: - - - Invalid index values or out of bounds indexes will end in `Invalid layer filtering` errors. - - Once a mapnik layer is selected, all mapnik layers will get blended. As this may change in the future **it is - recommended** to always select all mapnik layers if you want to select at least one so you will get a consistent - behavior in the future. - - Ordering is not considered. So right now filtering layers 0,3,4 is the very same thing as filtering 3,4,0. As this - may change in the future **it is recommended** to always select the layers in ascending order so you will get a - consistent behavior in the future. - -### Create JSONP - -The JSONP endpoint is provided in order to allow web browsers access which don't support CORS. - -#### Definition - -
-```bash -GET /api/v1/map?callback=method -``` - -#### Params - -- **config** - Encoded JSON with the params for creating named maps (the variables defined in the template). - -- **lmza** - This attribute contains the same as config but LZMA compressed. It cannot be used at the same time as `config`. - -- **callback** - JSON callback name. - -#### Example - -
REQUEST
-```bash -curl "https://documentation.cartodb.com/api/v1/map?callback=callback&config=%7B%22version%22%3A%221.0.1%22%2C%22layers%22%3A%5B%7B%22type%22%3A%22cartodb%22%2C%22options%22%3A%7B%22sql%22%3A%22select+%2A+from+european_countries_e%22%2C%22cartocss%22%3A%22%23european_countries_e%7B+polygon-fill%3A+%23FF6600%3B+%7D%22%2C%22cartocss_version%22%3A%222.3.0%22%2C%22interactivity%22%3A%5B%22cartodb_id%22%5D%7D%7D%5D%7D" -``` - -
RESPONSE
-```javascript -callback({ - layergroupid: "d9034c133262dfb90285cea26c5c7ad7:0", - cdn_url: { - "http": "http://cdb.com", - "https": "https://cdb.com" - }, - last_updated: "1970-01-01T00:00:00.000Z" -}) -``` - -### Remove - -Anonymous maps cannot be removed by an API call. They will expire after about five minutes but sometimes longer. If an anonymous map expires and tiles are requested from it, an error will be raised. This could happen if a user leaves a map open and after time, returns to the map and attempts to interact with it in a way that requires new tiles (e.g. zoom). The client will need to go through the steps of creating the map again to fix the problem. - - -## Named Maps - -Named maps are essentially the same as anonymous maps except the MapConfig is stored on the server and the map is given a unique name. Two other big differences are: you can create named maps from private data and that users without an API Key can see them even though they are from that private data. - -The main two differences compared to anonymous maps are: - -- **auth layer** - This allows you to control who is able to see the map based on a token auth - -- **templates** - Since the MapConfig is static it can contain some variables so the client can modify the map's appearance using those variables. - -Template maps are persistent with no preset expiration. They can only be created or deleted by a CartoDB user with a valid API_KEY (see auth section). - -### Create - -#### Definition - -
-```html -POST /api/v1/map/named -``` - -#### Params - -- **api_key** is required - -
template.json
-```javascript -{ - "version": "0.0.1", - "name": "template_name", - "auth": { - "method": "token", - "valid_tokens": [ - "auth_token1", - "auth_token2" - ] - }, - "placeholders": { - "color": { - "type": "css_color", - "default": "red" - }, - "cartodb_id": { - "type": "number", - "default": 1 - } - }, - "layergroup": { - "version": "1.0.1", - "layers": [ - { - "type": "cartodb", - "options": { - "cartocss_version": "2.1.1", - "cartocss": "#layer { polygon-fill: <%= color %>; }", - "sql": "select * from european_countries_e WHERE cartodb_id = <%= cartodb_id %>" - } - } - ] - }, - "view": { - "zoom": 4, - "center": { - "lng": 0, - "lat": 0 - }, - "bounds": { - "west": -45, - "south": -45, - "east": 45, - "north": 45 - } - } -} -``` - -##### Arguments - -- **name**: There can be at most _one_ template with the same name for any user. Valid names start with a letter or a number, and only contain letters, numbers, dashes (-) or underscores (_). -- **auth**: - - **method** `"token"` or `"open"` (the default if no `"method"` is given). - - **valid_tokens** when `"method"` is set to `"token"`, the values listed here allow you to instantiate the named map. -- **placeholders**: Variables not listed here are not substituted. Variables not provided at instantiation time trigger an error. A default is required for optional variables. Type specification is used for quoting, to avoid injections see template format section below. -- **layergroup**: the layer list definition. This is the MapConfig explained in anonymous maps. See [MapConfig documentation](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md) for more info. -- **view** (optional): extra keys to specify the compelling area for the map. It can be used to have a static preview of a named map without having to instantiate it. It is possible to specify it with `center` + `zoom` or with a bounding box `bbox`. Center+zoom takes precedence over bounding box. - - **zoom** The zoom level to use - - **center** - - **lng** The longitude to use for the center - - **lat** The latitude to use for the center - - **bounds** - - **west**: LowerCorner longitude for the bounding box, in decimal degrees (aka most western) - - **south**: LowerCorner latitude for the bounding box, in decimal degrees (aka most southern) - - **east**: UpperCorner longitude for the bounding box, in decimal degrees (aka most eastern) - - **north**: UpperCorner latitude for the bounding box, in decimal degrees (aka most northern) - -#### Template Format - -A templated `layergroup` allows the use of placeholders in the "cartocss" and "sql" elements of the "option" object in any "layer" of a `layergroup` configuration - -Valid placeholder names start with a letter and can only contain letters, numbers, or underscores. They have to be written between the `<%=` and `%>` strings in order to be replaced. - -##### Example - -```javascript -<%= my_color %> -``` - -The set of supported placeholders for a template will need to be explicitly defined with a specific type and default value for each. - -#### Placeholder Types - -The placeholder type will determine the kind of escaping for the associated value. Supported types are: - -- **sql_literal** internal single-quotes will be sql-escaped -- **sql_ident** internal double-quotes will be sql-escaped -- **number** can only contain numerical representation -- **css_color** can only contain color names or hex-values - -Placeholder default values will be used whenever new values are not provided as options at the time of creation on the client. They can also be used to test the template by creating a default version with new options provided. - -When using templates, be very careful about your selections as they can give broad access to your data if they are defined losely. - -
REQUEST
-```html -curl -X POST \ - -H 'Content-Type: application/json' \ - -d @template.json \ - 'https://documentation.cartodb.com/api/v1/map/named?api_key=APIKEY' -``` - -
RESPONSE
-```javascript -{ - "template_id":"name", -} -``` - -### Instantiate - -Instantiating a map allows you to get the information needed to fetch tiles. That temporal map is an anonymous map. - -#### Definition - -
-```html -POST /api/v1/map/named/:template_name -``` - -#### Param - -- **auth_token** optional, but required when `"method"` is set to `"token"` - -```javascript -// params.json -{ - "color": "#ff0000", - "cartodb_id": 3 -} -``` - -The fields you pass as `params.json` depend on the variables allowed by the named map. If there are variables missing it will raise an error (HTTP 400) - -- **auth_token** *optional* if the named map needs auth - -#### Example - -You can initialize a template map by passing all of the required parameters in a POST to `/api/v1/map/named/:template_name`. - -Valid credentials will be needed if required by the template. - -
REQUEST
-```bash -curl -X POST \ - -H 'Content-Type: application/json' \ - -d @params.json \ - 'https://documentation.cartodb.com/api/v1/map/named/@template_name?auth_token=AUTH_TOKEN' -``` - -
Response
-```javascript -{ - "layergroupid": "docs@fd2861af@c01a54877c62831bb51720263f91fb33:123456788", - "last_updated": "2013-11-14T11:20:15.000Z" -} -``` - -
Error
-```javascript -{ - "errors" : ["Some error string here"] -} -``` - -You can then use the `layergroupid` for fetching tiles and grids as you would normally (see anonymous map section). However you'll need to show the `auth_token`, if required by the template. - -### Using JSONP - -There is also a special endpoint to be able to initialize a map using JSONP (for old browsers). - -#### Definition - -
-```bash -GET /api/v1/map/named/:template_name/jsonp -``` - -#### Params - -- **auth_token** optional, but required when `"method"` is set to `"token"` -- **config** Encoded JSON with the params for creating named maps (the variables defined in the template) -- **lmza** This attribute contains the same as config but LZMA compressed. It cannot be used at the same time than `config`. -- **callback:** JSON callback name - -
REQUEST
-```bash -curl 'https://documentation.cartodb.com/api/v1/map/named/:template_name/jsonp?auth_token=AUTH_TOKEN&callback=callback&config=template_params_json' -``` - -
RESPONSE
-```javascript -callback({ - "layergroupid":"c01a54877c62831bb51720263f91fb33:0", - "last_updated":"1970-01-01T00:00:00.000Z" - "cdn_url": { - "http": "http://cdb.com", - "https": "https://cdb.com" - } -}) -``` - -This takes the `callback` function (required), `auth_token` if the template needs auth, and `config` which is the variable for the template (in cases where it has variables). - -```javascript -url += "config=" + encodeURIComponent( -JSON.stringify({ color: 'red' }); -``` - -The response is in this format: - -```javascript -callback({ - layergroupid: "dev@744bd0ed9b047f953fae673d56a47b4d:1390844463021.1401", - last_updated: "2014-01-27T17:41:03.021Z" -}) -``` - -### Update - -#### Definition - -
-```bash -PUT /api/v1/map/named/:template_name -``` - -#### Params - -- **api_key** is required - -#### Response - -Same as updating a map. - -#### Other Info - -Updating a named map removes all the named map instances so they need to be initialized again. - -#### Example - -
REQUEST
-```bash -curl -X PUT \ - -H 'Content-Type: application/json' \ - -d @template.json \ - 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' -``` - -
RESPONSE
-```javascript -{ - "template_id": "@template_name" -} -``` - -If any template has the same name, it will be updated. - -If a template with the same name does NOT exist, a 400 HTTP response is generated with an error in this format: - -```javascript -{ - "errors" : ["error string here"] -} -``` - -### Delete - -Delete the specified template map from the server and it disables any previously initialized versions of the map. - -#### Definition - -
-```bash -DELETE /api/v1/map/named/:template_name -``` - -#### Params - -- **api_key** is required - -#### Example - -
REQUEST
-```bash -curl -X DELETE 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' -``` - -
RESPONSE
-```javascript -{ - "errors" : ["Some error string here"] -} -``` - -On success, a 204 (No Content) response will be issued. Otherwise a 4xx response with an error will be returned. - -### Listing Available Templates - -This allows you to get a list of all available templates. - -#### Definition - -
-```bash -GET /api/v1/map/named/ -``` - -#### Params - -- **api_key** is required - -#### Example - -
REQUEST
-```bash -curl -X GET 'https://documentation.cartodb.com/api/v1/map/named?api_key=APIKEY' -``` - -
RESPONSE
-```javascript -{ - "template_ids": ["@template_name1","@template_name2"] -} -``` - -
ERROR
-```javascript -{ - "errors" : ["Some error string here"] -} -``` - -### Getting a Specific Template - -This gets the definition of a template. - -#### Definition - -
-```bash -GET /api/v1/map/named/:template_name -``` - -#### Params - -- **api_key** is required - -#### Example - -
REQUEST
-```bash -curl -X GET 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' -``` - -
RESPONSE
-```javascript -{ - "template": {...} // see template.json above -} -``` - -
ERROR
-```javascript -{ - "errors" : ["Some error string here"] -} -``` - -### Use with CartoDB.js -Named maps can be used with CartoDB.js by specifying a named map in a layer source as follows. Named maps are treated almost the same as other layer source types in most other ways. - -```js -var layerSource = { - user_name: '{your_user_name}', - type: 'namedmap', - named_map: { - name: '{template_name}', - layers: [{ - layer_name: "layer1", - interactivity: "column1, column2, ..." - }] - } -} - -cartodb.createLayer('map_dom_id',layerSource) - .addTo(map_object); - -``` - -[CartoDB.js](http://docs.cartodb.com/cartodb-platform/cartodb-js.html) has methods for accessing your named maps. - -1. [layer.setParams()](http://docs.cartodb.com/cartodb-platform/cartodb-js.html#layersetparamskey-value) allows you to change the template variables (in the placeholders object) via JavaScript -2. [layer.setAuthToken()](http://docs.cartodb.com/cartodb-platform/cartodb-js.html#layersetauthtokenauthtoken) allows you to set the auth tokens to create the layer - -## Static Maps API - -The Static Maps API can be initiated using both named and anonymous maps using the 'layergroupid' token. The API can be used to create static images of parts of maps and thumbnails for use in web design, graphic design, print, field work, and many other applications that require standard image formats. - -### Maps API endpoints - -Begin by instantiating either a named or anonymous map using the `layergroupid token` as demonstrated in the Maps API documentation above. The `layergroupid` token calls to the map and allows for parameters in the definition to generate static images. - -#### Zoom + center - -##### Definition - -
-```bash -GET /api/v1/map/static/center/:token/:z/:lat/:lng/:width/:height.:format -``` - -##### Params - -* **:token**: the layergroupid token from the map instantiation -* **:z**: the zoom level of the map -* **:lat**: the latitude for the center of the map -* **:lng**: the longitude for the center of the map -* **:width**: the width in pixels for the output image -* **:height**: the height in pixels for the output image -* **:format**: the format for the image, supported types: `png`, `jpg` - * **jpg** will have a default quality of 85. - -#### Bounding Box - -##### Definition - -
-```bash -GET /api/v1/map/static/bbox/:token/:bbox/:width/:height.:format` -``` - -##### Params - -* **:token**: the layergroupid token from the map instantiation -* **:bbox**: the bounding box in WGS 84 (EPSG:4326), comma separated values for: - - LowerCorner longitude, in decimal degrees (aka most western) - - LowerCorner latitude, in decimal degrees (aka most southern) - - UpperCorner longitude, in decimal degrees (aka most eastern) - - UpperCorner latitude, in decimal degrees (aka most northern) -* **:width**: the width in pixels for the output image -* **:height**: the height in pixels for the output image -* **:format**: the format for the image, supported types: `png`, `jpg` - * **jpg** will have a default quality of 85. - -Note: you can see this endpoint as: - -```bash -GET /api/v1/map/static/bbox/:token/:west,:south,:east,:north/:width/:height.:format` -``` - -#### Named map - -##### Definition - -
-```bash -GET /api/v1/map/static/named/:name/:width/:height.:format -``` - -##### Params - -* **:name**: the name of the named map -* **:width**: the width in pixels for the output image -* **:height**: the height in pixels for the output image -* **:format**: the format for the image, supported types: `png`, `jpg` - * **jpg** will have a default quality of 85. - -A named maps static image will get its constraints from the [view in the template](#Arguments), if `view` is not present it will estimate the extent based on the involved tables otherwise it fallback to `"zoom": 1`, `"lng": 0` and `"lat": 0`. - -####Layers - -The Static Maps API allows for multiple layers of incorporation into the `MapConfig` to allow for maximum versatility in creating a static map. The examples below were used to generate the static image example in the next section, and appear in the specific order designated. - -**Basemaps** - -```javascript - { - "type": "http", - "options": { - "urlTemplate": "http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png", - "subdomains": [ - "a", - "b", - "c" - ] - } - }, -``` - -By manipulating the `"urlTemplate"` custom basemaps can be used in generating static images. Supported map types for the Static Maps API are: - - 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', - 'http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png', - 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', - 'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', - -**Mapnik** - -```javascript - { - "type": "mapnik", - "options": { - "sql": "select null::geometry the_geom_webmercator", - "cartocss": "#layer {\n\tpolygon-fill: #FF3300;\n\tpolygon-opacity: 0;\n\tline-color: #333;\n\tline-width: 0;\n\tline-opacity: 0;\n}", - "cartocss_version": "2.2.0" - } - }, -``` - -**CartoDB** - -As described in the [Mapconfig documentation](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md), a "cartodb" type layer is now just an alias to a "mapnik" type layer as above, intended for backwards compatibility. - -```javascript - { - "type": "cartodb", - "options": { - "sql": "select * from park", - "cartocss": "/** simple visualization */\n\n#park{\n polygon-fill: #229A00;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}", - "cartocss_version": "2.1.1" - } - }, -``` - -Additionally, static images from Torque maps and other map layers can be used together to generate highly customizable and versatile static maps. - - -#### Caching - -It is important to note that generated images are cached from the live data referenced with the `layergroupid token` on the specified CartoDB account. This means that if the data changes, the cached image will also change. When linking dynamically, it is important to take into consideration the state of the data and longevity of the static image to avoid broken images or changes in how the image is displayed. To obtain a static snapshot of the map as it is today and preserve the image long-term regardless of changes in data, the image must be saved and stored locally. - -#### Limits - -* While images can encompass an entirety of a map, the default limit for pixel range is 8192 x 8192. -* Image resolution by default is set to 72 DPI -* JPEG quality by default is 85% -* Timeout limits for generating static maps are the same across the CartoDB Editor and Platform. It is important to ensure timely processing of queries. - - -### Examples - -After instantiating a map from a CartoDB account: - -
REQUEST
-```bash - GET /api/v1/map/static/center/4b615ff367e498e770e7d05e99181873:1420231989550.8699/14/40.71502926732618/-73.96039009094238/600/400.png -``` - -#### Response - -

static-api

- -#### MapConfig - -For this map, the multiple layers, order, and stylings are defined by the MapConfig. - -```javascript -{ - "version": "1.3.0", - "layers": [ - { - "type": "http", - "options": { - "urlTemplate": "http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png", - "subdomains": [ - "a", - "b", - "c" - ] - } - }, - { - "type": "mapnik", - "options": { - "sql": "select null::geometry the_geom_webmercator", - "cartocss": "#layer {\n\tpolygon-fill: #FF3300;\n\tpolygon-opacity: 0;\n\tline-color: #333;\n\tline-width: 0;\n\tline-opacity: 0;\n}", - "cartocss_version": "2.2.0" - } - }, - { - "type": "cartodb", - "options": { - "sql": "select * from park", - "cartocss": "/** simple visualization */\n\n#park{\n polygon-fill: #229A00;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}", - "cartocss_version": "2.1.1" - } - }, - { - "type": "cartodb", - "options": { - "sql": "select * from residential_zoning_2009", - "cartocss": "/** simple visualization */\n\n#residential_zoning_2009{\n polygon-fill: #c7eae5;\n polygon-opacity: 1;\n line-color: #FFF;\n line-width: 0.2;\n line-opacity: 0.5;\n}", - "cartocss_version": "2.1.1" - } - }, - { - "type": "cartodb", - "options": { - "sql": "select * from nycha_developments_july2011", - "cartocss": "/** simple visualization */\n\n#nycha_developments_july2011{\n polygon-fill: #ef3b2c;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}", - "cartocss_version": "2.1.1" - } - } - ] -} -``` +* [Quickstart](quickstart.md) +* [General Concepts](general_concepts.md) +* [Anonymous Maps](anonymous_maps.md) +* [Named Maps](named_maps.md) +* [Static Maps API](static_maps_api.md) diff --git a/docs/anonymous_maps.md b/docs/anonymous_maps.md new file mode 100644 index 00000000..79708384 --- /dev/null +++ b/docs/anonymous_maps.md @@ -0,0 +1,200 @@ +## Anonymous Maps + +Anonymous maps allows you to instantiate a map given SQL and CartoCSS. It also allows you to add interaction capabilities using [UTF Grid.](https://github.com/mapbox/utfgrid-spec) + +### Instantiate + +#### Definition + +
+```html +POST /api/v1/map +``` + +#### Params + +```javascript +{ + "version": "1.3.0", + "layers": [{ + "type": "mapnik", + "options": { + "cartocss_version": "2.1.1", + "cartocss": "#layer { polygon-fill: #FFF; }", + "sql": "select * from european_countries_e", + "interactivity": ["cartodb_id", "iso3"] + } + }] +} +``` + +Should be a [Mapconfig](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md). + +#### Response + +The response includes: + +- **layergroupid** + The ID for that map, used to compose the URL for the tiles. The final URL is: + + ```html + https://{account}.cartodb.com/api/v1/map/:layergroupid/{z}/{x}/{y}.png + ``` + +- **updated_at** + The ISO date of the last time the data involved in the query was updated. + +- **metadata** + Includes information about the layers. + - + +- **cdn_url** + URLs to fetch the data using the best CDN for your zone. + +#### Example + +
REQUEST
+```bash +curl 'https://documentation.cartodb.com/api/v1/map' -H 'Content-Type: application/json' -d @mapconfig.json +``` + +
RESPONSE
+```javascript +{ + "layergroupid": "c01a54877c62831bb51720263f91fb33:0", + "last_updated": "1970-01-01T00:00:00.000Z", + "metadata": { + "layers": [ + { + "type": "mapnik", + "meta": {} + } + ] + }, + "cdn_url": { + "http": "http://cdb.com", + "https": "https://cdb.com" + } +} +``` + +##### Retrieve resources from the layergroup + +###### Mapnik tiles can be accessed using: + +These tiles will get just the mapnik layers. To get individual layers see next section. + +```bash +https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/{z}/{x}/{y}.png +``` + +###### Individual layers + +The MapConfig specification holds the layers definition in a 0-based index. Layers can be requested individually in different formats depending on the layer type. + +Individual layers can be accessed using that 0-based index. For UTF grid tiles: + +```bash +https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer/{z}/{x}/{y}.grid.json +``` + +In this case, `:layer` as 0 returns the UTF grid tiles/attributes for layer 0, the only layer in the example MapConfig. + +If the MapConfig had a Torque layer at index 1 it could be possible to request it with: + +```bash +https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/1/{z}/{x}/{y}.torque.json +``` + +###### Attributes defined in `attributes` section: + +```bash +https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer/attributes/:feature_id +``` + +Which returns JSON with the attributes defined, like: + +```javascript +{ "c": 1, "d": 2 } +``` + +###### Blending and layer selection + +```bash +https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer_filter/{z}/{x}/{y}.png +``` + +Note: currently format is limited to `png`. + +`:layer_filter` can be used to select some layers to be rendered together. `:layer_filter` supports two formats: + +- `all` alias + +Using `all` as `:layer_filter` will blend all layers in the layergroup + +```bash +https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/all/{z}/{x}/{y}.png +``` + +- Filter by layer index + +A list of comma separated layer indexes can be used to just render a subset of layers. For example `0,3,4` will filter and blend layers with indexes 0, 3, and 4. + +```bash +https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/0,3,4/{z}/{x}/{y}.png +``` + +Some notes about filtering: + + - Invalid index values or out of bounds indexes will end in `Invalid layer filtering` errors. + - Once a mapnik layer is selected, all mapnik layers will get blended. As this may change in the future **it is + recommended** to always select all mapnik layers if you want to select at least one so you will get a consistent + behavior in the future. + - Ordering is not considered. So right now filtering layers 0,3,4 is the very same thing as filtering 3,4,0. As this + may change in the future **it is recommended** to always select the layers in ascending order so you will get a + consistent behavior in the future. + +### Create JSONP + +The JSONP endpoint is provided in order to allow web browsers access which don't support CORS. + +#### Definition + +
+```bash +GET /api/v1/map?callback=method +``` + +#### Params + +- **config** + Encoded JSON with the params for creating named maps (the variables defined in the template). + +- **lmza** + This attribute contains the same as config but LZMA compressed. It cannot be used at the same time as `config`. + +- **callback** + JSON callback name. + +#### Example + +
REQUEST
+```bash +curl "https://documentation.cartodb.com/api/v1/map?callback=callback&config=%7B%22version%22%3A%221.0.1%22%2C%22layers%22%3A%5B%7B%22type%22%3A%22cartodb%22%2C%22options%22%3A%7B%22sql%22%3A%22select+%2A+from+european_countries_e%22%2C%22cartocss%22%3A%22%23european_countries_e%7B+polygon-fill%3A+%23FF6600%3B+%7D%22%2C%22cartocss_version%22%3A%222.3.0%22%2C%22interactivity%22%3A%5B%22cartodb_id%22%5D%7D%7D%5D%7D" +``` + +
RESPONSE
+```javascript +callback({ + layergroupid: "d9034c133262dfb90285cea26c5c7ad7:0", + cdn_url: { + "http": "http://cdb.com", + "https": "https://cdb.com" + }, + last_updated: "1970-01-01T00:00:00.000Z" +}) +``` + +### Remove + +Anonymous maps cannot be removed by an API call. They will expire after about five minutes but sometimes longer. If an anonymous map expires and tiles are requested from it, an error will be raised. This could happen if a user leaves a map open and after time, returns to the map and attempts to interact with it in a way that requires new tiles (e.g. zoom). The client will need to go through the steps of creating the map again to fix the problem. diff --git a/docs/general_concepts.md b/docs/general_concepts.md new file mode 100644 index 00000000..3eccb780 --- /dev/null +++ b/docs/general_concepts.md @@ -0,0 +1,27 @@ +## General Concepts + +The following concepts are the same for every endpoint in the API except when it's noted explicitly. + +### Auth + +By default, users do not have access to private tables in CartoDB. In order to instantiate a map from private table data an API Key is required. Additionally, to include some endpoints, an API Key must be included (e.g. creating a named map). + +To execute an authorized request, `api_key=YOURAPIKEY` should be added to the request URL. The param can be also passed as POST param. Using HTTPS is mandatory when you are performing requests that include your `api_key`. + +### Errors + +Errors are reported using standard HTTP codes and extended information encoded in JSON with this format: + +```javascript +{ + "errors": [ + "access forbidden to table TABLE" + ] +} +``` + +If you use JSONP, the 200 HTTP code is always returned so the JavaScript client can receive errors from the JSON object. + +### CORS support + +All the endpoints, which might be accessed using a web browser, add CORS headers and allow OPTIONS method. diff --git a/docs/named_maps.md b/docs/named_maps.md new file mode 100644 index 00000000..efe74098 --- /dev/null +++ b/docs/named_maps.md @@ -0,0 +1,424 @@ +## Named Maps + +Named maps are essentially the same as anonymous maps except the MapConfig is stored on the server and the map is given a unique name. Two other big differences are: you can create named maps from private data and that users without an API Key can see them even though they are from that private data. + +The main two differences compared to anonymous maps are: + +- **auth layer** + This allows you to control who is able to see the map based on a token auth + +- **templates** + Since the MapConfig is static it can contain some variables so the client can modify the map's appearance using those variables. + +Template maps are persistent with no preset expiration. They can only be created or deleted by a CartoDB user with a valid API_KEY (see auth section). + +### Create + +#### Definition + +
+```html +POST /api/v1/map/named +``` + +#### Params + +- **api_key** is required + +
template.json
+```javascript +{ + "version": "0.0.1", + "name": "template_name", + "auth": { + "method": "token", + "valid_tokens": [ + "auth_token1", + "auth_token2" + ] + }, + "placeholders": { + "color": { + "type": "css_color", + "default": "red" + }, + "cartodb_id": { + "type": "number", + "default": 1 + } + }, + "layergroup": { + "version": "1.0.1", + "layers": [ + { + "type": "cartodb", + "options": { + "cartocss_version": "2.1.1", + "cartocss": "#layer { polygon-fill: <%= color %>; }", + "sql": "select * from european_countries_e WHERE cartodb_id = <%= cartodb_id %>" + } + } + ] + }, + "view": { + "zoom": 4, + "center": { + "lng": 0, + "lat": 0 + }, + "bounds": { + "west": -45, + "south": -45, + "east": 45, + "north": 45 + } + } +} +``` + +##### Arguments + +- **name**: There can be at most _one_ template with the same name for any user. Valid names start with a letter or a number, and only contain letters, numbers, dashes (-) or underscores (_). +- **auth**: + - **method** `"token"` or `"open"` (the default if no `"method"` is given). + - **valid_tokens** when `"method"` is set to `"token"`, the values listed here allow you to instantiate the named map. +- **placeholders**: Variables not listed here are not substituted. Variables not provided at instantiation time trigger an error. A default is required for optional variables. Type specification is used for quoting, to avoid injections see template format section below. +- **layergroup**: the layer list definition. This is the MapConfig explained in anonymous maps. See [MapConfig documentation](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md) for more info. +- **view** (optional): extra keys to specify the compelling area for the map. It can be used to have a static preview of a named map without having to instantiate it. It is possible to specify it with `center` + `zoom` or with a bounding box `bbox`. Center+zoom takes precedence over bounding box. + - **zoom** The zoom level to use + - **center** + - **lng** The longitude to use for the center + - **lat** The latitude to use for the center + - **bounds** + - **west**: LowerCorner longitude for the bounding box, in decimal degrees (aka most western) + - **south**: LowerCorner latitude for the bounding box, in decimal degrees (aka most southern) + - **east**: UpperCorner longitude for the bounding box, in decimal degrees (aka most eastern) + - **north**: UpperCorner latitude for the bounding box, in decimal degrees (aka most northern) + +#### Template Format + +A templated `layergroup` allows the use of placeholders in the "cartocss" and "sql" elements of the "option" object in any "layer" of a `layergroup` configuration + +Valid placeholder names start with a letter and can only contain letters, numbers, or underscores. They have to be written between the `<%=` and `%>` strings in order to be replaced. + +##### Example + +```javascript +<%= my_color %> +``` + +The set of supported placeholders for a template will need to be explicitly defined with a specific type and default value for each. + +#### Placeholder Types + +The placeholder type will determine the kind of escaping for the associated value. Supported types are: + +- **sql_literal** internal single-quotes will be sql-escaped +- **sql_ident** internal double-quotes will be sql-escaped +- **number** can only contain numerical representation +- **css_color** can only contain color names or hex-values + +Placeholder default values will be used whenever new values are not provided as options at the time of creation on the client. They can also be used to test the template by creating a default version with new options provided. + +When using templates, be very careful about your selections as they can give broad access to your data if they are defined losely. + +
REQUEST
+```html +curl -X POST \ + -H 'Content-Type: application/json' \ + -d @template.json \ + 'https://documentation.cartodb.com/api/v1/map/named?api_key=APIKEY' +``` + +
RESPONSE
+```javascript +{ + "template_id":"name", +} +``` + +### Instantiate + +Instantiating a map allows you to get the information needed to fetch tiles. That temporal map is an anonymous map. + +#### Definition + +
+```html +POST /api/v1/map/named/:template_name +``` + +#### Param + +- **auth_token** optional, but required when `"method"` is set to `"token"` + +```javascript +// params.json +{ + "color": "#ff0000", + "cartodb_id": 3 +} +``` + +The fields you pass as `params.json` depend on the variables allowed by the named map. If there are variables missing it will raise an error (HTTP 400) + +- **auth_token** *optional* if the named map needs auth + +#### Example + +You can initialize a template map by passing all of the required parameters in a POST to `/api/v1/map/named/:template_name`. + +Valid credentials will be needed if required by the template. + +
REQUEST
+```bash +curl -X POST \ + -H 'Content-Type: application/json' \ + -d @params.json \ + 'https://documentation.cartodb.com/api/v1/map/named/@template_name?auth_token=AUTH_TOKEN' +``` + +
Response
+```javascript +{ + "layergroupid": "docs@fd2861af@c01a54877c62831bb51720263f91fb33:123456788", + "last_updated": "2013-11-14T11:20:15.000Z" +} +``` + +
Error
+```javascript +{ + "errors" : ["Some error string here"] +} +``` + +You can then use the `layergroupid` for fetching tiles and grids as you would normally (see anonymous map section). However you'll need to show the `auth_token`, if required by the template. + +### Using JSONP + +There is also a special endpoint to be able to initialize a map using JSONP (for old browsers). + +#### Definition + +
+```bash +GET /api/v1/map/named/:template_name/jsonp +``` + +#### Params + +- **auth_token** optional, but required when `"method"` is set to `"token"` +- **config** Encoded JSON with the params for creating named maps (the variables defined in the template) +- **lmza** This attribute contains the same as config but LZMA compressed. It cannot be used at the same time than `config`. +- **callback:** JSON callback name + +
REQUEST
+```bash +curl 'https://documentation.cartodb.com/api/v1/map/named/:template_name/jsonp?auth_token=AUTH_TOKEN&callback=callback&config=template_params_json' +``` + +
RESPONSE
+```javascript +callback({ + "layergroupid":"c01a54877c62831bb51720263f91fb33:0", + "last_updated":"1970-01-01T00:00:00.000Z" + "cdn_url": { + "http": "http://cdb.com", + "https": "https://cdb.com" + } +}) +``` + +This takes the `callback` function (required), `auth_token` if the template needs auth, and `config` which is the variable for the template (in cases where it has variables). + +```javascript +url += "config=" + encodeURIComponent( +JSON.stringify({ color: 'red' }); +``` + +The response is in this format: + +```javascript +callback({ + layergroupid: "dev@744bd0ed9b047f953fae673d56a47b4d:1390844463021.1401", + last_updated: "2014-01-27T17:41:03.021Z" +}) +``` + +### Update + +#### Definition + +
+```bash +PUT /api/v1/map/named/:template_name +``` + +#### Params + +- **api_key** is required + +#### Response + +Same as updating a map. + +#### Other Info + +Updating a named map removes all the named map instances so they need to be initialized again. + +#### Example + +
REQUEST
+```bash +curl -X PUT \ + -H 'Content-Type: application/json' \ + -d @template.json \ + 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' +``` + +
RESPONSE
+```javascript +{ + "template_id": "@template_name" +} +``` + +If any template has the same name, it will be updated. + +If a template with the same name does NOT exist, a 400 HTTP response is generated with an error in this format: + +```javascript +{ + "errors" : ["error string here"] +} +``` + +### Delete + +Delete the specified template map from the server and it disables any previously initialized versions of the map. + +#### Definition + +
+```bash +DELETE /api/v1/map/named/:template_name +``` + +#### Params + +- **api_key** is required + +#### Example + +
REQUEST
+```bash +curl -X DELETE 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' +``` + +
RESPONSE
+```javascript +{ + "errors" : ["Some error string here"] +} +``` + +On success, a 204 (No Content) response will be issued. Otherwise a 4xx response with an error will be returned. + +### Listing Available Templates + +This allows you to get a list of all available templates. + +#### Definition + +
+```bash +GET /api/v1/map/named/ +``` + +#### Params + +- **api_key** is required + +#### Example + +
REQUEST
+```bash +curl -X GET 'https://documentation.cartodb.com/api/v1/map/named?api_key=APIKEY' +``` + +
RESPONSE
+```javascript +{ + "template_ids": ["@template_name1","@template_name2"] +} +``` + +
ERROR
+```javascript +{ + "errors" : ["Some error string here"] +} +``` + +### Getting a Specific Template + +This gets the definition of a template. + +#### Definition + +
+```bash +GET /api/v1/map/named/:template_name +``` + +#### Params + +- **api_key** is required + +#### Example + +
REQUEST
+```bash +curl -X GET 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' +``` + +
RESPONSE
+```javascript +{ + "template": {...} // see template.json above +} +``` + +
ERROR
+```javascript +{ + "errors" : ["Some error string here"] +} +``` + +### Use with CartoDB.js +Named maps can be used with CartoDB.js by specifying a named map in a layer source as follows. Named maps are treated almost the same as other layer source types in most other ways. + +```js +var layerSource = { + user_name: '{your_user_name}', + type: 'namedmap', + named_map: { + name: '{template_name}', + layers: [{ + layer_name: "layer1", + interactivity: "column1, column2, ..." + }] + } +} + +cartodb.createLayer('map_dom_id',layerSource) + .addTo(map_object); + +``` + +[CartoDB.js](http://docs.cartodb.com/cartodb-platform/cartodb-js.html) has methods for accessing your named maps. + +1. [layer.setParams()](http://docs.cartodb.com/cartodb-platform/cartodb-js.html#layersetparamskey-value) allows you to change the template variables (in the placeholders object) via JavaScript +2. [layer.setAuthToken()](http://docs.cartodb.com/cartodb-platform/cartodb-js.html#layersetauthtokenauthtoken) allows you to set the auth tokens to create the layer diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 00000000..76e7c6e9 --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,105 @@ +## Quickstart + +You can create two types of maps with the Maps API: + +- **Anonymous maps** + You can create maps using your CartoDB public data. Any client can change the read-only SQL and CartoCSS parameters that generate the map tiles. These maps can be created from a JavaScript application alone and no authenticated calls are needed. See [this CartoDB.js example]({{ '/cartodb-platform/cartodb-js.html' | prepend: site.baseurl }}). + +- **Named maps** + There are also maps that have access to your private data. These maps require an owner to setup and modify any SQL and CartoCSS parameters and are not modifiable without new setup calls. + +### Anonymous maps + +Here is an example of how to create an anonymous map with JavaScript: + +```javascript +var mapconfig = { + "version": "1.3.1", + "layers": [{ + "type": "cartodb", + "options": { + "cartocss_version": "2.1.1", + "cartocss": "#layer { polygon-fill: #FFF; }", + "sql": "select * from european_countries_e" + } + }] +} + +$.ajax({ + crossOrigin: true, + type: 'POST', + dataType: 'json', + contentType: 'application/json', + url: 'https://documentation.cartodb.com/api/v1/map', + data: JSON.stringify(mapconfig), + success: function(data) { + var templateUrl = 'https://documentation.cartodb.com/api/v1/map/' + data.layergroupid + '/{z}/{x}/{y}.png' + console.log(templateUrl); + } +}) +``` + +### Named maps + +Let's create a named map using some private tables in a CartoDB account. +The following map config sets up a map of European countries that have a white fill color: + +```javascript +{ + "version": "0.0.1", + "name": "test", + "auth": { + "method": "open" + }, + "layergroup": { + "layers": [{ + "type": "mapnik", + "options": { + "cartocss_version": "2.1.1", + "cartocss": "#layer { polygon-fill: #FFF; }", + "sql": "select * from european_countries_e" + } + }] + } +} +``` + +The map config needs to be sent to CartoDB's Map API using an authenticated call. Here we will use a command line tool called `curl`. For more info about this tool, see [this blog post](http://quickleft.com/blog/command-line-tutorials-curl), or type ``man curl`` in bash. Using `curl`, and storing the config from above in a file `mapconfig.json`, the call would look like: + +
+```bash +curl 'https://{account}.cartodb.com/api/v1/map/named?api_key=APIKEY' -H 'Content-Type: application/json' -d @mapconfig.json +``` + +To get the `URL` to fetch the tiles you need to instantiate the map, where `template_id` is the template name from the previous response. + +
+```bash +curl -X POST 'https://{account}.cartodb.com/api/v1/map/named/:template_id' -H 'Content-Type: application/json' +``` + +The response will return JSON with properties for the `layergroupid`, the timestamp (`last_updated`) of the last data modification and some key/value pairs with `metadata` for the `layers`. +Note: all `layers` in `metadata` will always have a `type` string and a `meta` dictionary with the key/value pairs. + +Here is an example response: + +```javascript +{ + "layergroupid": "c01a54877c62831bb51720263f91fb33:0", + "last_updated": "1970-01-01T00:00:00.000Z", + "metadata": { + "layers": [ + { + "type": "mapnik", + "meta": {} + } + ] + } +} +``` + +You can use the `layergroupid` to instantiate a URL template for accessing tiles on the client. Here we use the `layergroupid` from the example response above in this URL template: + +```bash +https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/{z}/{x}/{y}.png +``` diff --git a/docs/static_maps_api.md b/docs/static_maps_api.md new file mode 100644 index 00000000..8f9c22ad --- /dev/null +++ b/docs/static_maps_api.md @@ -0,0 +1,212 @@ +# Static Maps API + +The Static Maps API can be initiated using both named and anonymous maps using the 'layergroupid' token. The API can be used to create static images of parts of maps and thumbnails for use in web design, graphic design, print, field work, and many other applications that require standard image formats. + +## Maps API endpoints + +Begin by instantiating either a named or anonymous map using the `layergroupid token` as demonstrated in the Maps API documentation above. The `layergroupid` token calls to the map and allows for parameters in the definition to generate static images. + +### Zoom + center + +#### Definition + +
+```bash +GET /api/v1/map/static/center/:token/:z/:lat/:lng/:width/:height.:format +``` + +#### Params + +* **:token**: the layergroupid token from the map instantiation +* **:z**: the zoom level of the map +* **:lat**: the latitude for the center of the map +* **:lng**: the longitude for the center of the map +* **:width**: the width in pixels for the output image +* **:height**: the height in pixels for the output image +* **:format**: the format for the image, supported types: `png`, `jpg` + * **jpg** will have a default quality of 85. + +### Bounding Box + +#### Definition + +
+```bash +GET /api/v1/map/static/bbox/:token/:bbox/:width/:height.:format` +``` + +#### Params + +* **:token**: the layergroupid token from the map instantiation +* **:bbox**: the bounding box in WGS 84 (EPSG:4326), comma separated values for: + - LowerCorner longitude, in decimal degrees (aka most western) + - LowerCorner latitude, in decimal degrees (aka most southern) + - UpperCorner longitude, in decimal degrees (aka most eastern) + - UpperCorner latitude, in decimal degrees (aka most northern) +* **:width**: the width in pixels for the output image +* **:height**: the height in pixels for the output image +* **:format**: the format for the image, supported types: `png`, `jpg` + * **jpg** will have a default quality of 85. + +Note: you can see this endpoint as: + +```bash +GET /api/v1/map/static/bbox/:token/:west,:south,:east,:north/:width/:height.:format` +``` + +### Named map + +#### Definition + +
+```bash +GET /api/v1/map/static/named/:name/:width/:height.:format +``` + +#### Params + +* **:name**: the name of the named map +* **:width**: the width in pixels for the output image +* **:height**: the height in pixels for the output image +* **:format**: the format for the image, supported types: `png`, `jpg` + * **jpg** will have a default quality of 85. + +A named maps static image will get its constraints from the [view in the template](#Arguments), if `view` is not present it will estimate the extent based on the involved tables otherwise it fallback to `"zoom": 1`, `"lng": 0` and `"lat": 0`. + +####Layers + +The Static Maps API allows for multiple layers of incorporation into the `MapConfig` to allow for maximum versatility in creating a static map. The examples below were used to generate the static image example in the next section, and appear in the specific order designated. + +**Basemaps** + +```javascript + { + "type": "http", + "options": { + "urlTemplate": "http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png", + "subdomains": [ + "a", + "b", + "c" + ] + } + }, +``` + +By manipulating the `"urlTemplate"` custom basemaps can be used in generating static images. Supported map types for the Static Maps API are: + + 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', + 'http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png', + 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', + 'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', + +**Mapnik** + +```javascript + { + "type": "mapnik", + "options": { + "sql": "select null::geometry the_geom_webmercator", + "cartocss": "#layer {\n\tpolygon-fill: #FF3300;\n\tpolygon-opacity: 0;\n\tline-color: #333;\n\tline-width: 0;\n\tline-opacity: 0;\n}", + "cartocss_version": "2.2.0" + } + }, +``` + +**CartoDB** + +As described in the [Mapconfig documentation](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md), a "cartodb" type layer is now just an alias to a "mapnik" type layer as above, intended for backwards compatibility. + +```javascript + { + "type": "cartodb", + "options": { + "sql": "select * from park", + "cartocss": "/** simple visualization */\n\n#park{\n polygon-fill: #229A00;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}", + "cartocss_version": "2.1.1" + } + }, +``` + +Additionally, static images from Torque maps and other map layers can be used together to generate highly customizable and versatile static maps. + + +### Caching + +It is important to note that generated images are cached from the live data referenced with the `layergroupid token` on the specified CartoDB account. This means that if the data changes, the cached image will also change. When linking dynamically, it is important to take into consideration the state of the data and longevity of the static image to avoid broken images or changes in how the image is displayed. To obtain a static snapshot of the map as it is today and preserve the image long-term regardless of changes in data, the image must be saved and stored locally. + +### Limits + +* While images can encompass an entirety of a map, the default limit for pixel range is 8192 x 8192. +* Image resolution by default is set to 72 DPI +* JPEG quality by default is 85% +* Timeout limits for generating static maps are the same across the CartoDB Editor and Platform. It is important to ensure timely processing of queries. + + +## Examples + +After instantiating a map from a CartoDB account: + +
REQUEST
+```bash + GET /api/v1/map/static/center/4b615ff367e498e770e7d05e99181873:1420231989550.8699/14/40.71502926732618/-73.96039009094238/600/400.png +``` + +### Response + +

static-api

+ +### MapConfig + +For this map, the multiple layers, order, and stylings are defined by the MapConfig. + +```javascript +{ + "version": "1.3.0", + "layers": [ + { + "type": "http", + "options": { + "urlTemplate": "http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png", + "subdomains": [ + "a", + "b", + "c" + ] + } + }, + { + "type": "mapnik", + "options": { + "sql": "select null::geometry the_geom_webmercator", + "cartocss": "#layer {\n\tpolygon-fill: #FF3300;\n\tpolygon-opacity: 0;\n\tline-color: #333;\n\tline-width: 0;\n\tline-opacity: 0;\n}", + "cartocss_version": "2.2.0" + } + }, + { + "type": "cartodb", + "options": { + "sql": "select * from park", + "cartocss": "/** simple visualization */\n\n#park{\n polygon-fill: #229A00;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}", + "cartocss_version": "2.1.1" + } + }, + { + "type": "cartodb", + "options": { + "sql": "select * from residential_zoning_2009", + "cartocss": "/** simple visualization */\n\n#residential_zoning_2009{\n polygon-fill: #c7eae5;\n polygon-opacity: 1;\n line-color: #FFF;\n line-width: 0.2;\n line-opacity: 0.5;\n}", + "cartocss_version": "2.1.1" + } + }, + { + "type": "cartodb", + "options": { + "sql": "select * from nycha_developments_july2011", + "cartocss": "/** simple visualization */\n\n#nycha_developments_july2011{\n polygon-fill: #ef3b2c;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}", + "cartocss_version": "2.1.1" + } + } + ] +} +``` From 5e0c9377f238824c3de46cbf84722ff025754bc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Thu, 22 Oct 2015 15:02:01 +0200 Subject: [PATCH 02/33] newdocs: fix titles --- docs/anonymous_maps.md | 32 +++++++++---------- docs/general_concepts.md | 8 ++--- docs/named_maps.md | 68 ++++++++++++++++++++-------------------- docs/quickstart.md | 6 ++-- 4 files changed, 57 insertions(+), 57 deletions(-) diff --git a/docs/anonymous_maps.md b/docs/anonymous_maps.md index 79708384..69e7632b 100644 --- a/docs/anonymous_maps.md +++ b/docs/anonymous_maps.md @@ -1,17 +1,17 @@ -## Anonymous Maps +# Anonymous Maps Anonymous maps allows you to instantiate a map given SQL and CartoCSS. It also allows you to add interaction capabilities using [UTF Grid.](https://github.com/mapbox/utfgrid-spec) -### Instantiate +## Instantiate -#### Definition +### Definition
```html POST /api/v1/map ``` -#### Params +### Params ```javascript { @@ -30,7 +30,7 @@ POST /api/v1/map Should be a [Mapconfig](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md). -#### Response +### Response The response includes: @@ -51,7 +51,7 @@ The response includes: - **cdn_url** URLs to fetch the data using the best CDN for your zone. -#### Example +### Example
REQUEST
```bash @@ -78,9 +78,9 @@ curl 'https://documentation.cartodb.com/api/v1/map' -H 'Content-Type: applicatio } ``` -##### Retrieve resources from the layergroup +#### Retrieve resources from the layergroup -###### Mapnik tiles can be accessed using: +##### Mapnik tiles can be accessed using: These tiles will get just the mapnik layers. To get individual layers see next section. @@ -88,7 +88,7 @@ These tiles will get just the mapnik layers. To get individual layers see next s https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/{z}/{x}/{y}.png ``` -###### Individual layers +##### Individual layers The MapConfig specification holds the layers definition in a 0-based index. Layers can be requested individually in different formats depending on the layer type. @@ -106,7 +106,7 @@ If the MapConfig had a Torque layer at index 1 it could be possible to request i https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/1/{z}/{x}/{y}.torque.json ``` -###### Attributes defined in `attributes` section: +##### Attributes defined in `attributes` section: ```bash https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer/attributes/:feature_id @@ -118,7 +118,7 @@ Which returns JSON with the attributes defined, like: { "c": 1, "d": 2 } ``` -###### Blending and layer selection +##### Blending and layer selection ```bash https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer_filter/{z}/{x}/{y}.png @@ -154,18 +154,18 @@ Some notes about filtering: may change in the future **it is recommended** to always select the layers in ascending order so you will get a consistent behavior in the future. -### Create JSONP +## Create JSONP The JSONP endpoint is provided in order to allow web browsers access which don't support CORS. -#### Definition +### Definition
```bash GET /api/v1/map?callback=method ``` -#### Params +### Params - **config** Encoded JSON with the params for creating named maps (the variables defined in the template). @@ -176,7 +176,7 @@ GET /api/v1/map?callback=method - **callback** JSON callback name. -#### Example +### Example
REQUEST
```bash @@ -195,6 +195,6 @@ callback({ }) ``` -### Remove +## Remove Anonymous maps cannot be removed by an API call. They will expire after about five minutes but sometimes longer. If an anonymous map expires and tiles are requested from it, an error will be raised. This could happen if a user leaves a map open and after time, returns to the map and attempts to interact with it in a way that requires new tiles (e.g. zoom). The client will need to go through the steps of creating the map again to fix the problem. diff --git a/docs/general_concepts.md b/docs/general_concepts.md index 3eccb780..859c6df9 100644 --- a/docs/general_concepts.md +++ b/docs/general_concepts.md @@ -1,14 +1,14 @@ -## General Concepts +# General Concepts The following concepts are the same for every endpoint in the API except when it's noted explicitly. -### Auth +## Auth By default, users do not have access to private tables in CartoDB. In order to instantiate a map from private table data an API Key is required. Additionally, to include some endpoints, an API Key must be included (e.g. creating a named map). To execute an authorized request, `api_key=YOURAPIKEY` should be added to the request URL. The param can be also passed as POST param. Using HTTPS is mandatory when you are performing requests that include your `api_key`. -### Errors +## Errors Errors are reported using standard HTTP codes and extended information encoded in JSON with this format: @@ -22,6 +22,6 @@ Errors are reported using standard HTTP codes and extended information encoded i If you use JSONP, the 200 HTTP code is always returned so the JavaScript client can receive errors from the JSON object. -### CORS support +## CORS support All the endpoints, which might be accessed using a web browser, add CORS headers and allow OPTIONS method. diff --git a/docs/named_maps.md b/docs/named_maps.md index efe74098..50bfb659 100644 --- a/docs/named_maps.md +++ b/docs/named_maps.md @@ -1,4 +1,4 @@ -## Named Maps +# Named Maps Named maps are essentially the same as anonymous maps except the MapConfig is stored on the server and the map is given a unique name. Two other big differences are: you can create named maps from private data and that users without an API Key can see them even though they are from that private data. @@ -12,16 +12,16 @@ The main two differences compared to anonymous maps are: Template maps are persistent with no preset expiration. They can only be created or deleted by a CartoDB user with a valid API_KEY (see auth section). -### Create +## Create -#### Definition +### Definition
```html POST /api/v1/map/named ``` -#### Params +### Params - **api_key** is required @@ -76,7 +76,7 @@ POST /api/v1/map/named } ``` -##### Arguments +#### Arguments - **name**: There can be at most _one_ template with the same name for any user. Valid names start with a letter or a number, and only contain letters, numbers, dashes (-) or underscores (_). - **auth**: @@ -95,13 +95,13 @@ POST /api/v1/map/named - **east**: UpperCorner longitude for the bounding box, in decimal degrees (aka most eastern) - **north**: UpperCorner latitude for the bounding box, in decimal degrees (aka most northern) -#### Template Format +### Template Format A templated `layergroup` allows the use of placeholders in the "cartocss" and "sql" elements of the "option" object in any "layer" of a `layergroup` configuration Valid placeholder names start with a letter and can only contain letters, numbers, or underscores. They have to be written between the `<%=` and `%>` strings in order to be replaced. -##### Example +#### Example ```javascript <%= my_color %> @@ -109,7 +109,7 @@ Valid placeholder names start with a letter and can only contain letters, number The set of supported placeholders for a template will need to be explicitly defined with a specific type and default value for each. -#### Placeholder Types +### Placeholder Types The placeholder type will determine the kind of escaping for the associated value. Supported types are: @@ -137,18 +137,18 @@ curl -X POST \ } ``` -### Instantiate +## Instantiate Instantiating a map allows you to get the information needed to fetch tiles. That temporal map is an anonymous map. -#### Definition +### Definition
```html POST /api/v1/map/named/:template_name ``` -#### Param +### Param - **auth_token** optional, but required when `"method"` is set to `"token"` @@ -164,7 +164,7 @@ The fields you pass as `params.json` depend on the variables allowed by the name - **auth_token** *optional* if the named map needs auth -#### Example +### Example You can initialize a template map by passing all of the required parameters in a POST to `/api/v1/map/named/:template_name`. @@ -195,18 +195,18 @@ curl -X POST \ You can then use the `layergroupid` for fetching tiles and grids as you would normally (see anonymous map section). However you'll need to show the `auth_token`, if required by the template. -### Using JSONP +## Using JSONP There is also a special endpoint to be able to initialize a map using JSONP (for old browsers). -#### Definition +### Definition
```bash GET /api/v1/map/named/:template_name/jsonp ``` -#### Params +### Params - **auth_token** optional, but required when `"method"` is set to `"token"` - **config** Encoded JSON with the params for creating named maps (the variables defined in the template) @@ -246,28 +246,28 @@ callback({ }) ``` -### Update +## Update -#### Definition +### Definition
```bash PUT /api/v1/map/named/:template_name ``` -#### Params +### Params - **api_key** is required -#### Response +### Response Same as updating a map. -#### Other Info +### Other Info Updating a named map removes all the named map instances so they need to be initialized again. -#### Example +### Example
REQUEST
```bash @@ -294,22 +294,22 @@ If a template with the same name does NOT exist, a 400 HTTP response is generate } ``` -### Delete +## Delete Delete the specified template map from the server and it disables any previously initialized versions of the map. -#### Definition +### Definition
```bash DELETE /api/v1/map/named/:template_name ``` -#### Params +### Params - **api_key** is required -#### Example +### Example
REQUEST
```bash @@ -325,22 +325,22 @@ curl -X DELETE 'https://documentation.cartodb.com/api/v1/map/named/:template_nam On success, a 204 (No Content) response will be issued. Otherwise a 4xx response with an error will be returned. -### Listing Available Templates +## Listing Available Templates This allows you to get a list of all available templates. -#### Definition +### Definition
```bash GET /api/v1/map/named/ ``` -#### Params +### Params - **api_key** is required -#### Example +### Example
REQUEST
```bash @@ -361,22 +361,22 @@ curl -X GET 'https://documentation.cartodb.com/api/v1/map/named?api_key=APIKEY' } ``` -### Getting a Specific Template +## Getting a Specific Template This gets the definition of a template. -#### Definition +### Definition
```bash GET /api/v1/map/named/:template_name ``` -#### Params +### Params - **api_key** is required -#### Example +### Example
REQUEST
```bash @@ -397,7 +397,7 @@ curl -X GET 'https://documentation.cartodb.com/api/v1/map/named/:template_name?a } ``` -### Use with CartoDB.js +## Use with CartoDB.js Named maps can be used with CartoDB.js by specifying a named map in a layer source as follows. Named maps are treated almost the same as other layer source types in most other ways. ```js diff --git a/docs/quickstart.md b/docs/quickstart.md index 76e7c6e9..5952a26a 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,4 +1,4 @@ -## Quickstart +# Quickstart You can create two types of maps with the Maps API: @@ -8,7 +8,7 @@ You can create two types of maps with the Maps API: - **Named maps** There are also maps that have access to your private data. These maps require an owner to setup and modify any SQL and CartoCSS parameters and are not modifiable without new setup calls. -### Anonymous maps +## Anonymous maps Here is an example of how to create an anonymous map with JavaScript: @@ -39,7 +39,7 @@ $.ajax({ }) ``` -### Named maps +## Named maps Let's create a named map using some private tables in a CartoDB account. The following map config sets up a map of European countries that have a white fill color: From 36b91180e49cbbfc4f836841c4407b1c1d62b712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 15:51:31 +0100 Subject: [PATCH 03/33] docs: quickstart --- docs/quickstart.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/quickstart.md b/docs/quickstart.md index 5952a26a..43768b77 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -3,7 +3,7 @@ You can create two types of maps with the Maps API: - **Anonymous maps** - You can create maps using your CartoDB public data. Any client can change the read-only SQL and CartoCSS parameters that generate the map tiles. These maps can be created from a JavaScript application alone and no authenticated calls are needed. See [this CartoDB.js example]({{ '/cartodb-platform/cartodb-js.html' | prepend: site.baseurl }}). + You can create maps using your CartoDB public data. Any client can change the read-only SQL and CartoCSS parameters that generate the map tiles. These maps can be created from a JavaScript application alone and no authenticated calls are needed. See [this CartoDB.js example](/cartodb-platform/cartodb-js/). - **Named maps** There are also maps that have access to your private data. These maps require an owner to setup and modify any SQL and CartoCSS parameters and are not modifiable without new setup calls. @@ -64,24 +64,27 @@ The following map config sets up a map of European countries that have a white f } ``` -The map config needs to be sent to CartoDB's Map API using an authenticated call. Here we will use a command line tool called `curl`. For more info about this tool, see [this blog post](http://quickleft.com/blog/command-line-tutorials-curl), or type ``man curl`` in bash. Using `curl`, and storing the config from above in a file `mapconfig.json`, the call would look like: +The map config needs to be sent to CartoDB's Map API using an authenticated call. Here we will use a command line tool called `curl`. For more info about this tool, see [this blog post](http://quickleft.com/blog/command-line-tutorials-curl), or type `man curl` in bash. Using `curl`, and storing the config from above in a file `mapconfig.json`, the call would look like: + +#### Call -
```bash curl 'https://{account}.cartodb.com/api/v1/map/named?api_key=APIKEY' -H 'Content-Type: application/json' -d @mapconfig.json ``` To get the `URL` to fetch the tiles you need to instantiate the map, where `template_id` is the template name from the previous response. -
+#### Call + ```bash curl -X POST 'https://{account}.cartodb.com/api/v1/map/named/:template_id' -H 'Content-Type: application/json' ``` The response will return JSON with properties for the `layergroupid`, the timestamp (`last_updated`) of the last data modification and some key/value pairs with `metadata` for the `layers`. + Note: all `layers` in `metadata` will always have a `type` string and a `meta` dictionary with the key/value pairs. -Here is an example response: +#### Response ```javascript { From 50a943c131f831c8c0a05f3c2af7bcaed51b29b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 15:53:39 +0100 Subject: [PATCH 04/33] docs: quickstart --- docs/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/quickstart.md b/docs/quickstart.md index 43768b77..3fb26ad1 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -3,7 +3,7 @@ You can create two types of maps with the Maps API: - **Anonymous maps** - You can create maps using your CartoDB public data. Any client can change the read-only SQL and CartoCSS parameters that generate the map tiles. These maps can be created from a JavaScript application alone and no authenticated calls are needed. See [this CartoDB.js example](/cartodb-platform/cartodb-js/). + You can create maps using your CartoDB public data. Any client can change the read-only SQL and CartoCSS parameters that generate the map tiles. These maps can be created from a JavaScript application alone and no authenticated calls are needed. See [this CartoDB.js example](/cartodb-platform/cartodb-js/getting-started/). - **Named maps** There are also maps that have access to your private data. These maps require an owner to setup and modify any SQL and CartoCSS parameters and are not modifiable without new setup calls. From 90487819bf28c38cd57a6007fb210653da035205 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 16:02:23 +0100 Subject: [PATCH 05/33] docs: anonymous_maps --- docs/anonymous_maps.md | 85 +++++++++++++++++++----------------------- 1 file changed, 39 insertions(+), 46 deletions(-) diff --git a/docs/anonymous_maps.md b/docs/anonymous_maps.md index 69e7632b..cb62a238 100644 --- a/docs/anonymous_maps.md +++ b/docs/anonymous_maps.md @@ -2,16 +2,16 @@ Anonymous maps allows you to instantiate a map given SQL and CartoCSS. It also allows you to add interaction capabilities using [UTF Grid.](https://github.com/mapbox/utfgrid-spec) + ## Instantiate -### Definition +#### Definition -
```html POST /api/v1/map ``` -### Params +#### Params ```javascript { @@ -30,35 +30,28 @@ POST /api/v1/map Should be a [Mapconfig](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md). -### Response +#### Response The response includes: -- **layergroupid** - The ID for that map, used to compose the URL for the tiles. The final URL is: - - ```html - https://{account}.cartodb.com/api/v1/map/:layergroupid/{z}/{x}/{y}.png - ``` - -- **updated_at** - The ISO date of the last time the data involved in the query was updated. - -- **metadata** - Includes information about the layers. - - - -- **cdn_url** - URLs to fetch the data using the best CDN for your zone. +Attributes | Description +--- | --- +layergroupid | The ID for that map, used to compose the URL for the tiles. The final URL is: ```html + https://{account}.cartodb.com/api/v1/map/:layergroupid/{z}/{x}/{y}.png``` +updated_at | The ISO date of the last time the data involved in the query was updated. +metadata | Includes information about the layers. +cdn_url | URLs to fetch the data using the best CDN for your zone. ### Example -
REQUEST
+#### Call + ```bash curl 'https://documentation.cartodb.com/api/v1/map' -H 'Content-Type: application/json' -d @mapconfig.json ``` -
RESPONSE
+#### Response + ```javascript { "layergroupid": "c01a54877c62831bb51720263f91fb33:0", @@ -78,9 +71,9 @@ curl 'https://documentation.cartodb.com/api/v1/map' -H 'Content-Type: applicatio } ``` -#### Retrieve resources from the layergroup +### Retrieve resources from the layergroup -##### Mapnik tiles can be accessed using: +#### Mapnik tiles can be accessed using These tiles will get just the mapnik layers. To get individual layers see next section. @@ -88,7 +81,7 @@ These tiles will get just the mapnik layers. To get individual layers see next s https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/{z}/{x}/{y}.png ``` -##### Individual layers +#### Individual layers The MapConfig specification holds the layers definition in a 0-based index. Layers can be requested individually in different formats depending on the layer type. @@ -106,7 +99,7 @@ If the MapConfig had a Torque layer at index 1 it could be possible to request i https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/1/{z}/{x}/{y}.torque.json ``` -##### Attributes defined in `attributes` section: +#### Attributes defined in `attributes` section ```bash https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer/attributes/:feature_id @@ -118,7 +111,7 @@ Which returns JSON with the attributes defined, like: { "c": 1, "d": 2 } ``` -##### Blending and layer selection +#### Blending and layer selection ```bash https://documentation.cartodb.com/api/v1/map/c01a54877c62831bb51720263f91fb33:0/:layer_filter/{z}/{x}/{y}.png @@ -154,47 +147,47 @@ Some notes about filtering: may change in the future **it is recommended** to always select the layers in ascending order so you will get a consistent behavior in the future. + ## Create JSONP The JSONP endpoint is provided in order to allow web browsers access which don't support CORS. -### Definition +#### Definition -
```bash GET /api/v1/map?callback=method ``` -### Params +#### Params -- **config** - Encoded JSON with the params for creating named maps (the variables defined in the template). - -- **lmza** - This attribute contains the same as config but LZMA compressed. It cannot be used at the same time as `config`. - -- **callback** - JSON callback name. +Param | Description +--- | --- +config | Encoded JSON with the params for creating named maps (the variables defined in the template). +lmza | This attribute contains the same as config but LZMA compressed. It cannot be used at the same time as `config`. +callback | JSON callback name. ### Example -
REQUEST
+#### Call + ```bash curl "https://documentation.cartodb.com/api/v1/map?callback=callback&config=%7B%22version%22%3A%221.0.1%22%2C%22layers%22%3A%5B%7B%22type%22%3A%22cartodb%22%2C%22options%22%3A%7B%22sql%22%3A%22select+%2A+from+european_countries_e%22%2C%22cartocss%22%3A%22%23european_countries_e%7B+polygon-fill%3A+%23FF6600%3B+%7D%22%2C%22cartocss_version%22%3A%222.3.0%22%2C%22interactivity%22%3A%5B%22cartodb_id%22%5D%7D%7D%5D%7D" ``` -
RESPONSE
+#### Response + ```javascript callback({ - layergroupid: "d9034c133262dfb90285cea26c5c7ad7:0", - cdn_url: { - "http": "http://cdb.com", - "https": "https://cdb.com" - }, - last_updated: "1970-01-01T00:00:00.000Z" + layergroupid: "d9034c133262dfb90285cea26c5c7ad7:0", + cdn_url: { + "http": "http://cdb.com", + "https": "https://cdb.com" + }, + last_updated: "1970-01-01T00:00:00.000Z" }) ``` + ## Remove Anonymous maps cannot be removed by an API call. They will expire after about five minutes but sometimes longer. If an anonymous map expires and tiles are requested from it, an error will be raised. This could happen if a user leaves a map open and after time, returns to the map and attempts to interact with it in a way that requires new tiles (e.g. zoom). The client will need to go through the steps of creating the map again to fix the problem. From 2c35e27095bccdf44c0f0c174b26290770cb7e4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 16:07:04 +0100 Subject: [PATCH 06/33] docs: anonymous_maps --- docs/anonymous_maps.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/anonymous_maps.md b/docs/anonymous_maps.md index cb62a238..ead1ce96 100644 --- a/docs/anonymous_maps.md +++ b/docs/anonymous_maps.md @@ -36,8 +36,7 @@ The response includes: Attributes | Description --- | --- -layergroupid | The ID for that map, used to compose the URL for the tiles. The final URL is: ```html - https://{account}.cartodb.com/api/v1/map/:layergroupid/{z}/{x}/{y}.png``` +layergroupid | The ID for that map, used to compose the URL for the tiles. The final URL is: `https://{account}.cartodb.com/api/v1/map/:layergroupid/{z}/{x}/{y}.png` updated_at | The ISO date of the last time the data involved in the query was updated. metadata | Includes information about the layers. cdn_url | URLs to fetch the data using the best CDN for your zone. From 3eda1750cc7120950fce4cd7ebb160e22dd6dd5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 16:26:33 +0100 Subject: [PATCH 07/33] docs: named maps --- docs/named_maps.md | 182 +++++++++++++++++++++++++++------------------ 1 file changed, 110 insertions(+), 72 deletions(-) diff --git a/docs/named_maps.md b/docs/named_maps.md index 50bfb659..fc9b5954 100644 --- a/docs/named_maps.md +++ b/docs/named_maps.md @@ -14,18 +14,20 @@ Template maps are persistent with no preset expiration. They can only be created ## Create -### Definition +#### Definition -
```html POST /api/v1/map/named ``` -### Params +#### Params -- **api_key** is required +Params | Description +--- | --- +api_key | is required + +#### template.json -
template.json
```javascript { "version": "0.0.1", @@ -78,22 +80,32 @@ POST /api/v1/map/named #### Arguments -- **name**: There can be at most _one_ template with the same name for any user. Valid names start with a letter or a number, and only contain letters, numbers, dashes (-) or underscores (_). -- **auth**: - - **method** `"token"` or `"open"` (the default if no `"method"` is given). - - **valid_tokens** when `"method"` is set to `"token"`, the values listed here allow you to instantiate the named map. -- **placeholders**: Variables not listed here are not substituted. Variables not provided at instantiation time trigger an error. A default is required for optional variables. Type specification is used for quoting, to avoid injections see template format section below. -- **layergroup**: the layer list definition. This is the MapConfig explained in anonymous maps. See [MapConfig documentation](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md) for more info. -- **view** (optional): extra keys to specify the compelling area for the map. It can be used to have a static preview of a named map without having to instantiate it. It is possible to specify it with `center` + `zoom` or with a bounding box `bbox`. Center+zoom takes precedence over bounding box. - - **zoom** The zoom level to use - - **center** - - **lng** The longitude to use for the center - - **lat** The latitude to use for the center - - **bounds** - - **west**: LowerCorner longitude for the bounding box, in decimal degrees (aka most western) - - **south**: LowerCorner latitude for the bounding box, in decimal degrees (aka most southern) - - **east**: UpperCorner longitude for the bounding box, in decimal degrees (aka most eastern) - - **north**: UpperCorner latitude for the bounding box, in decimal degrees (aka most northern) +Params | Description +--- | --- +name | There can be at most _one_ template with the same name for any user. Valid names start with a letter or a number, and only contain letters, numbers, dashes (-) or underscores (_). + +auth | +--- | --- +|_ method | `"token"` or `"open"` (the default if no `"method"` is given). +|_ valid_tokens | when `"method"` is set to `"token"`, the values listed here allow you to instantiate the named map. +placeholders | Variables not listed here are not substituted. Variables not provided at instantiation time trigger an error. A default is required for optional variables. Type specification is used for quoting, to avoid injections see template format section below. +layergroup | the layer list definition. This is the MapConfig explained in anonymous maps. See [MapConfig documentation](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md) for more info. + +view (optional) | extra keys to specify the compelling area for the map. It can be used to have a static preview of a named map without having to instantiate it. It is possible to specify it with `center` + `zoom` or with a bounding box `bbox`. Center+zoom takes precedence over bounding box. +--- | --- +|_ zoom | The zoom level to use + +|_ center | +--- | --- +|_ |_ lng | The longitude to use for the center +|_ |_ lat | The latitude to use for the center + +|_ bounds | +--- | --- +|_ |_ west | LowerCorner longitude for the bounding box, in decimal degrees (aka most western) +|_ |_ south | LowerCorner latitude for the bounding box, in decimal degrees (aka most southern) +|_ |_ east | UpperCorner longitude for the bounding box, in decimal degrees (aka most eastern) +|_ |_ north | UpperCorner latitude for the bounding box, in decimal degrees (aka most northern) ### Template Format @@ -113,16 +125,19 @@ The set of supported placeholders for a template will need to be explicitly defi The placeholder type will determine the kind of escaping for the associated value. Supported types are: -- **sql_literal** internal single-quotes will be sql-escaped -- **sql_ident** internal double-quotes will be sql-escaped -- **number** can only contain numerical representation -- **css_color** can only contain color names or hex-values +Types | Description +--- | --- +sql_literal | internal single-quotes will be sql-escaped +sql_ident | internal double-quotes will be sql-escaped +number | can only contain numerical representation +css_color | can only contain color names or hex-values Placeholder default values will be used whenever new values are not provided as options at the time of creation on the client. They can also be used to test the template by creating a default version with new options provided. When using templates, be very careful about your selections as they can give broad access to your data if they are defined losely. -
REQUEST
+#### Call + ```html curl -X POST \ -H 'Content-Type: application/json' \ @@ -130,7 +145,8 @@ curl -X POST \ 'https://documentation.cartodb.com/api/v1/map/named?api_key=APIKEY' ``` -
RESPONSE
+#### Response + ```javascript { "template_id":"name", @@ -141,16 +157,17 @@ curl -X POST \ Instantiating a map allows you to get the information needed to fetch tiles. That temporal map is an anonymous map. -### Definition +#### Definition -
```html POST /api/v1/map/named/:template_name ``` -### Param +#### Param -- **auth_token** optional, but required when `"method"` is set to `"token"` +Param | Description +--- | --- +auth_token | optional, but required when `"method"` is set to `"token"` ```javascript // params.json @@ -162,15 +179,15 @@ POST /api/v1/map/named/:template_name The fields you pass as `params.json` depend on the variables allowed by the named map. If there are variables missing it will raise an error (HTTP 400) -- **auth_token** *optional* if the named map needs auth - ### Example You can initialize a template map by passing all of the required parameters in a POST to `/api/v1/map/named/:template_name`. Valid credentials will be needed if required by the template. -
REQUEST
+ +#### Call + ```bash curl -X POST \ -H 'Content-Type: application/json' \ @@ -178,7 +195,8 @@ curl -X POST \ 'https://documentation.cartodb.com/api/v1/map/named/@template_name?auth_token=AUTH_TOKEN' ``` -
Response
+#### Response + ```javascript { "layergroupid": "docs@fd2861af@c01a54877c62831bb51720263f91fb33:123456788", @@ -186,39 +204,43 @@ curl -X POST \ } ``` -
Error
+#### Error + ```javascript { "errors" : ["Some error string here"] } ``` -You can then use the `layergroupid` for fetching tiles and grids as you would normally (see anonymous map section). However you'll need to show the `auth_token`, if required by the template. +You can then use the `layergroupid` for fetching tiles and grids as you would normally (see anonymous map section). However you'll need to show the `auth_token`, if required by the template. ## Using JSONP There is also a special endpoint to be able to initialize a map using JSONP (for old browsers). -### Definition +#### Definition -
```bash GET /api/v1/map/named/:template_name/jsonp ``` -### Params +#### Params -- **auth_token** optional, but required when `"method"` is set to `"token"` -- **config** Encoded JSON with the params for creating named maps (the variables defined in the template) -- **lmza** This attribute contains the same as config but LZMA compressed. It cannot be used at the same time than `config`. -- **callback:** JSON callback name +Params | Description +--- | --- +auth_token | optional, but required when `"method"` is set to `"token"` +config | Encoded JSON with the params for creating named maps (the variables defined in the template) +lmza | This attribute contains the same as config but LZMA compressed. It cannot be used at the same time than `config`. +callback | JSON callback name + +#### Call -
REQUEST
```bash curl 'https://documentation.cartodb.com/api/v1/map/named/:template_name/jsonp?auth_token=AUTH_TOKEN&callback=callback&config=template_params_json' ``` -
RESPONSE
+#### Response + ```javascript callback({ "layergroupid":"c01a54877c62831bb51720263f91fb33:0", @@ -248,18 +270,20 @@ callback({ ## Update -### Definition +#### Definition
```bash PUT /api/v1/map/named/:template_name ``` -### Params +#### Params -- **api_key** is required +Param | Description +--- | --- +api_key | is required -### Response +#### Response Same as updating a map. @@ -269,7 +293,8 @@ Updating a named map removes all the named map instances so they need to be init ### Example -
REQUEST
+#### Call + ```bash curl -X PUT \ -H 'Content-Type: application/json' \ @@ -277,7 +302,8 @@ curl -X PUT \ 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' ``` -
RESPONSE
+#### Response + ```javascript { "template_id": "@template_name" @@ -298,25 +324,29 @@ If a template with the same name does NOT exist, a 400 HTTP response is generate Delete the specified template map from the server and it disables any previously initialized versions of the map. -### Definition +#### Definition
```bash DELETE /api/v1/map/named/:template_name ``` -### Params +#### Params -- **api_key** is required +Param | Description +--- | --- +api_key | is required ### Example -
REQUEST
+#### Call + ```bash curl -X DELETE 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' ``` -
RESPONSE
+#### Response + ```javascript { "errors" : ["Some error string here"] @@ -329,35 +359,39 @@ On success, a 204 (No Content) response will be issued. Otherwise a 4xx response This allows you to get a list of all available templates. -### Definition +#### Definition -
```bash GET /api/v1/map/named/ ``` -### Params +#### Params -- **api_key** is required +Param | Description +--- | --- +api_key | is required ### Example -
REQUEST
+#### Call + ```bash curl -X GET 'https://documentation.cartodb.com/api/v1/map/named?api_key=APIKEY' ``` -
RESPONSE
+#### Response + ```javascript { "template_ids": ["@template_name1","@template_name2"] } ``` -
ERROR
+#### Error + ```javascript { - "errors" : ["Some error string here"] + "errors" : ["Some error string here"] } ``` @@ -365,32 +399,36 @@ curl -X GET 'https://documentation.cartodb.com/api/v1/map/named?api_key=APIKEY' This gets the definition of a template. -### Definition +#### Definition -
```bash GET /api/v1/map/named/:template_name ``` -### Params +#### Params -- **api_key** is required +Param | Description +--- | --- +api_key | is required ### Example -
REQUEST
+#### Call + ```bash curl -X GET 'https://documentation.cartodb.com/api/v1/map/named/:template_name?api_key=APIKEY' ``` -
RESPONSE
+#### Response + ```javascript { "template": {...} // see template.json above } ``` -
ERROR
+#### Error + ```javascript { "errors" : ["Some error string here"] From 8087f838ef291090a3c1187be2be3e67a2c66c77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 16:46:50 +0100 Subject: [PATCH 08/33] docs: named maps --- docs/named_maps.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/named_maps.md b/docs/named_maps.md index fc9b5954..217653ba 100644 --- a/docs/named_maps.md +++ b/docs/named_maps.md @@ -456,7 +456,7 @@ cartodb.createLayer('map_dom_id',layerSource) ``` -[CartoDB.js](http://docs.cartodb.com/cartodb-platform/cartodb-js.html) has methods for accessing your named maps. +[CartoDB.js](http://docs.cartodb.com/cartodb-platform/cartodb-js/) has methods for accessing your named maps. -1. [layer.setParams()](http://docs.cartodb.com/cartodb-platform/cartodb-js.html#layersetparamskey-value) allows you to change the template variables (in the placeholders object) via JavaScript -2. [layer.setAuthToken()](http://docs.cartodb.com/cartodb-platform/cartodb-js.html#layersetauthtokenauthtoken) allows you to set the auth tokens to create the layer +1. [layer.setParams()](http://docs.cartodb.com/cartodb-platform/cartodb-js/api-methods/#layersetparamskey-value) allows you to change the template variables (in the placeholders object) via JavaScript +2. [layer.setAuthToken()](http://docs.cartodb.com/cartodb-platform/cartodb-js/api-methods/#layersetauthtokenauthtoken) allows you to set the auth tokens to create the layer From cc0ebf70a75783f65969d70e66e5cd53e72f149f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 16:55:11 +0100 Subject: [PATCH 09/33] docs: static maps --- docs/static_maps_api.md | 111 ++++++++++++++++++++++------------------ 1 file changed, 61 insertions(+), 50 deletions(-) diff --git a/docs/static_maps_api.md b/docs/static_maps_api.md index 8f9c22ad..ff97673b 100644 --- a/docs/static_maps_api.md +++ b/docs/static_maps_api.md @@ -17,38 +17,43 @@ GET /api/v1/map/static/center/:token/:z/:lat/:lng/:width/:height.:format #### Params -* **:token**: the layergroupid token from the map instantiation -* **:z**: the zoom level of the map -* **:lat**: the latitude for the center of the map -* **:lng**: the longitude for the center of the map -* **:width**: the width in pixels for the output image -* **:height**: the height in pixels for the output image -* **:format**: the format for the image, supported types: `png`, `jpg` - * **jpg** will have a default quality of 85. +Param | Description +--- | --- +:token | the layergroupid token from the map instantiation +:z | the zoom level of the map +:lat | the latitude for the center of the map + +:format | the format for the image, supported types: `png`, `jpg` +--- | --- +|_ jpg | will have a default quality of 85. ### Bounding Box #### Definition -
```bash GET /api/v1/map/static/bbox/:token/:bbox/:width/:height.:format` ``` #### Params -* **:token**: the layergroupid token from the map instantiation -* **:bbox**: the bounding box in WGS 84 (EPSG:4326), comma separated values for: - - LowerCorner longitude, in decimal degrees (aka most western) - - LowerCorner latitude, in decimal degrees (aka most southern) - - UpperCorner longitude, in decimal degrees (aka most eastern) - - UpperCorner latitude, in decimal degrees (aka most northern) -* **:width**: the width in pixels for the output image -* **:height**: the height in pixels for the output image -* **:format**: the format for the image, supported types: `png`, `jpg` - * **jpg** will have a default quality of 85. +Param | Description +--- | --- +:token | the layergroupid token from the map instantiation -Note: you can see this endpoint as: +:bbox | the bounding box in WGS 84 (EPSG:4326), comma separated values for: +--- | --- + | LowerCorner longitude, in decimal degrees (aka most western) + | LowerCorner latitude, in decimal degrees (aka most southern) + | UpperCorner longitude, in decimal degrees (aka most eastern) + | UpperCorner latitude, in decimal degrees (aka most northern) +:width | the width in pixels for the output image +:height | the height in pixels for the output image +:format | the format for the image, supported types: `png`, `jpg` + +:format | the bounding box in WGS 84 (EPSG:4326), comma separated values for: +--- | --- +|_ jpg | will have a default quality of 85. ```bash GET /api/v1/map/static/bbox/:token/:west,:south,:east,:north/:width/:height.:format` @@ -58,22 +63,26 @@ GET /api/v1/map/static/bbox/:token/:west,:south,:east,:north/:width/:height.:for #### Definition -
```bash GET /api/v1/map/static/named/:name/:width/:height.:format ``` #### Params -* **:name**: the name of the named map -* **:width**: the width in pixels for the output image -* **:height**: the height in pixels for the output image -* **:format**: the format for the image, supported types: `png`, `jpg` - * **jpg** will have a default quality of 85. +Param | Description +--- | --- +:name | the name of the named map +:width | the width in pixels for the output image +:height | the height in pixels for the output image +:height | the height in pixels for the output image + +:format | the format for the image, supported types: `png`, `jpg` +--- | --- +|_ jpg | will have a default quality of 85. A named maps static image will get its constraints from the [view in the template](#Arguments), if `view` is not present it will estimate the extent based on the involved tables otherwise it fallback to `"zoom": 1`, `"lng": 0` and `"lat": 0`. -####Layers +#### Layers The Static Maps API allows for multiple layers of incorporation into the `MapConfig` to allow for maximum versatility in creating a static map. The examples below were used to generate the static image example in the next section, and appear in the specific order designated. @@ -95,22 +104,24 @@ The Static Maps API allows for multiple layers of incorporation into the `MapCon By manipulating the `"urlTemplate"` custom basemaps can be used in generating static images. Supported map types for the Static Maps API are: - 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', - 'http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png', - 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', - 'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', +``` +'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', +'http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png', +'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', +'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', +``` **Mapnik** ```javascript - { - "type": "mapnik", - "options": { - "sql": "select null::geometry the_geom_webmercator", - "cartocss": "#layer {\n\tpolygon-fill: #FF3300;\n\tpolygon-opacity: 0;\n\tline-color: #333;\n\tline-width: 0;\n\tline-opacity: 0;\n}", - "cartocss_version": "2.2.0" - } - }, +{ + "type": "mapnik", + "options": { + "sql": "select null::geometry the_geom_webmercator", + "cartocss": "#layer {\n\tpolygon-fill: #FF3300;\n\tpolygon-opacity: 0;\n\tline-color: #333;\n\tline-width: 0;\n\tline-opacity: 0;\n}", + "cartocss_version": "2.2.0" + } +}, ``` **CartoDB** @@ -118,14 +129,14 @@ By manipulating the `"urlTemplate"` custom basemaps can be used in generating st As described in the [Mapconfig documentation](https://github.com/CartoDB/Windshaft/blob/0.44.1/doc/MapConfig-1.3.0.md), a "cartodb" type layer is now just an alias to a "mapnik" type layer as above, intended for backwards compatibility. ```javascript - { - "type": "cartodb", - "options": { - "sql": "select * from park", - "cartocss": "/** simple visualization */\n\n#park{\n polygon-fill: #229A00;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}", - "cartocss_version": "2.1.1" - } - }, +{ + "type": "cartodb", + "options": { + "sql": "select * from park", + "cartocss": "/** simple visualization */\n\n#park{\n polygon-fill: #229A00;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}", + "cartocss_version": "2.1.1" + } +} ``` Additionally, static images from Torque maps and other map layers can be used together to generate highly customizable and versatile static maps. @@ -142,17 +153,17 @@ It is important to note that generated images are cached from the live data refe * JPEG quality by default is 85% * Timeout limits for generating static maps are the same across the CartoDB Editor and Platform. It is important to ensure timely processing of queries. - ## Examples After instantiating a map from a CartoDB account: -
REQUEST
+#### Call + ```bash GET /api/v1/map/static/center/4b615ff367e498e770e7d05e99181873:1420231989550.8699/14/40.71502926732618/-73.96039009094238/600/400.png ``` -### Response +#### Response

static-api

From cd00680c807f9c5eaf0d459eefed2e2fd61193c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 17:00:22 +0100 Subject: [PATCH 10/33] docs: static maps --- docs/static_maps_api.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/static_maps_api.md b/docs/static_maps_api.md index ff97673b..a806b8bb 100644 --- a/docs/static_maps_api.md +++ b/docs/static_maps_api.md @@ -89,17 +89,17 @@ The Static Maps API allows for multiple layers of incorporation into the `MapCon **Basemaps** ```javascript - { - "type": "http", - "options": { - "urlTemplate": "http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png", - "subdomains": [ - "a", - "b", - "c" - ] - } - }, +{ + "type": "http", + "options": { + "urlTemplate": "http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png", + "subdomains": [ + "a", + "b", + "c" + ] + } +} ``` By manipulating the `"urlTemplate"` custom basemaps can be used in generating static images. Supported map types for the Static Maps API are: From 034b49278834c1bceca86394bcba9146a09c0b6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 17:02:16 +0100 Subject: [PATCH 11/33] docs: static maps --- docs/static_maps_api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/static_maps_api.md b/docs/static_maps_api.md index a806b8bb..15c313c3 100644 --- a/docs/static_maps_api.md +++ b/docs/static_maps_api.md @@ -104,7 +104,7 @@ The Static Maps API allows for multiple layers of incorporation into the `MapCon By manipulating the `"urlTemplate"` custom basemaps can be used in generating static images. Supported map types for the Static Maps API are: -``` +```javascript 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', 'http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png', 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', From a3c7b3fc352a448b6a97b3fd5e9a98d569b7d542 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 17:31:20 +0100 Subject: [PATCH 12/33] docs: fixes --- docs/named_maps.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/named_maps.md b/docs/named_maps.md index 217653ba..bf64153a 100644 --- a/docs/named_maps.md +++ b/docs/named_maps.md @@ -179,6 +179,8 @@ auth_token | optional, but required when `"method"` is set to `"token"` The fields you pass as `params.json` depend on the variables allowed by the named map. If there are variables missing it will raise an error (HTTP 400) +- **auth_token** *optional* if the named map needs auth + ### Example You can initialize a template map by passing all of the required parameters in a POST to `/api/v1/map/named/:template_name`. From 277c0ee818408f32d7b964a31e6817ba4766cebc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Wed, 28 Oct 2015 17:38:46 +0100 Subject: [PATCH 13/33] docs: fixes --- docs/static_maps_api.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/static_maps_api.md b/docs/static_maps_api.md index 15c313c3..537e672f 100644 --- a/docs/static_maps_api.md +++ b/docs/static_maps_api.md @@ -55,6 +55,8 @@ Param | Description --- | --- |_ jpg | will have a default quality of 85. +Note: you can see this endpoint as + ```bash GET /api/v1/map/static/bbox/:token/:west,:south,:east,:north/:width/:height.:format` ``` From b2cd421e2e44f399df15ad9c0fe7ea5909396fc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Thu, 29 Oct 2015 16:59:51 +0100 Subject: [PATCH 14/33] docs: rearrange overview --- docs/Map-API.md | 8 ++++++++ docs/quickstart.md | 8 -------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/Map-API.md b/docs/Map-API.md index a93af594..bb74d209 100644 --- a/docs/Map-API.md +++ b/docs/Map-API.md @@ -2,6 +2,14 @@ The CartoDB Maps API allows you to generate maps based on data hosted in your CartoDB account and you can apply custom SQL and CartoCSS to the data. The API generates a XYZ-based URL to fetch Web Mercator projected tiles using web clients such as [Leaflet](http://leafletjs.com), [Google Maps](https://developers.google.com/maps/), or [OpenLayers](http://openlayers.org/). +You can create two types of maps with the Maps API: + +- **Anonymous maps** + You can create maps using your CartoDB public data. Any client can change the read-only SQL and CartoCSS parameters that generate the map tiles. These maps can be created from a JavaScript application alone and no authenticated calls are needed. See [this CartoDB.js example](/cartodb-platform/cartodb-js/getting-started/). + +- **Named maps** + There are also maps that have access to your private data. These maps require an owner to setup and modify any SQL and CartoCSS parameters and are not modifiable without new setup calls. + ## Documentation * [Quickstart](quickstart.md) diff --git a/docs/quickstart.md b/docs/quickstart.md index 3fb26ad1..00f084df 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,13 +1,5 @@ # Quickstart -You can create two types of maps with the Maps API: - -- **Anonymous maps** - You can create maps using your CartoDB public data. Any client can change the read-only SQL and CartoCSS parameters that generate the map tiles. These maps can be created from a JavaScript application alone and no authenticated calls are needed. See [this CartoDB.js example](/cartodb-platform/cartodb-js/getting-started/). - -- **Named maps** - There are also maps that have access to your private data. These maps require an owner to setup and modify any SQL and CartoCSS parameters and are not modifiable without new setup calls. - ## Anonymous maps Here is an example of how to create an anonymous map with JavaScript: From 4bc8c577290355519a7b8cb47223f96d63a7c466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Matall=C3=ADn?= Date: Fri, 30 Oct 2015 11:25:42 +0100 Subject: [PATCH 15/33] docs: remove code-title --- docs/named_maps.md | 2 -- docs/static_maps_api.md | 1 - 2 files changed, 3 deletions(-) diff --git a/docs/named_maps.md b/docs/named_maps.md index bf64153a..29303cbc 100644 --- a/docs/named_maps.md +++ b/docs/named_maps.md @@ -274,7 +274,6 @@ callback({ #### Definition -
```bash PUT /api/v1/map/named/:template_name ``` @@ -328,7 +327,6 @@ Delete the specified template map from the server and it disables any previously #### Definition -
```bash DELETE /api/v1/map/named/:template_name ``` diff --git a/docs/static_maps_api.md b/docs/static_maps_api.md index 537e672f..1d6f3160 100644 --- a/docs/static_maps_api.md +++ b/docs/static_maps_api.md @@ -10,7 +10,6 @@ Begin by instantiating either a named or anonymous map using the `layergroupid t #### Definition -
```bash GET /api/v1/map/static/center/:token/:z/:lat/:lng/:width/:height.:format ``` From cd847adfb3441291b34a0e181c9491f44f339775 Mon Sep 17 00:00:00 2001 From: Paul Norman Date: Mon, 28 Dec 2015 11:53:54 -0800 Subject: [PATCH 16/33] Fix readme typo [no ci] --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 8f0d46f4..891050db 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,6 @@ Examples -------- [CartoDB's Map Gallery](http://cartodb.com/gallery/) showcases several examples of visualisations built on top of this. -m Contributing --- From 5ac327272f0b8538e385b19cdb2b9f623c7879b7 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 30 Dec 2015 15:52:52 +0100 Subject: [PATCH 17/33] Do not test `all` layers. Test is also present in windshaft suite. --- test/acceptance/ported/blend_http_fallback.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/acceptance/ported/blend_http_fallback.js b/test/acceptance/ported/blend_http_fallback.js index 7d0d89c2..3c35c5fc 100644 --- a/test/acceptance/ported/blend_http_fallback.js +++ b/test/acceptance/ported/blend_http_fallback.js @@ -86,7 +86,7 @@ describe('blend http fallback', function() { }; var filteredLayersSuite = [ - ['all'], // layers displayed: 2 + 4, skipping 3 as it fails + //['all'], // layers displayed: 2 + 4, skipping 3 as it fails [0, 4], [0, 3], // skips layer 3 as it fails [1, 2], From 76cbc2f863e270ec310bd551d0846d97167bc503 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 30 Dec 2015 17:44:49 +0100 Subject: [PATCH 18/33] Improve PgQueryRunner public run method Last param is callback function, receiving err + result, no need to keep passing two functions, the query handler and the final callback. It should be easier to understand now as query handler was in a position where it had to know about receiving a callback, that was exposing an implementation detail of PgQueryRunner. --- lib/cartodb/api/query_tables_api.js | 86 +++++++++++-------------- lib/cartodb/api/tables_extent_api.js | 28 ++++---- lib/cartodb/backends/pg_query_runner.js | 13 ++-- test/acceptance/multilayer_server.js | 8 +-- 4 files changed, 65 insertions(+), 70 deletions(-) diff --git a/lib/cartodb/api/query_tables_api.js b/lib/cartodb/api/query_tables_api.js index f7667bfe..af2fc978 100644 --- a/lib/cartodb/api/query_tables_api.js +++ b/lib/cartodb/api/query_tables_api.js @@ -13,26 +13,22 @@ module.exports = QueryTablesApi; QueryTablesApi.prototype.getAffectedTablesInQuery = function (username, sql, callback) { - var query = 'SELECT CDB_QueryTablesText($windshaft$' + prepareSql(sql) + '$windshaft$)'; - this.pgQueryRunner.run(username, query, handleAffectedTablesInQueryRows, callback); + this.pgQueryRunner.run(username, query, function handleAffectedTablesInQueryRows (err, rows) { + if (err){ + var msg = err.message ? err.message : err; + callback(new Error('could not fetch source tables: ' + msg)); + return; + } + + // This is an Array, so no need to split into parts + var tableNames = rows[0].cdb_querytablestext; + return callback(null, tableNames); + }); }; -function handleAffectedTablesInQueryRows(err, rows, callback) { - if (err){ - var msg = err.message ? err.message : err; - callback(new Error('could not fetch source tables: ' + msg)); - return; - } - - // This is an Array, so no need to split into parts - var tableNames = rows[0].cdb_querytablestext; - callback(null, tableNames); -} - QueryTablesApi.prototype.getAffectedTablesAndLastUpdatedTime = function (username, sql, callback) { - var query = [ 'WITH querytables AS (', 'SELECT * FROM CDB_QueryTablesText($windshaft$' + prepareSql(sql) + '$windshaft$) as tablenames', @@ -42,28 +38,26 @@ QueryTablesApi.prototype.getAffectedTablesAndLastUpdatedTime = function (usernam 'WHERE m.tabname = any ((SELECT tablenames from querytables)::regclass[])' ].join(' '); - this.pgQueryRunner.run(username, query, handleAffectedTablesAndLastUpdatedTimeRows, callback); -}; + this.pgQueryRunner.run(username, query, function handleAffectedTablesAndLastUpdatedTimeRows (err, rows) { + if (err || rows.length === 0) { + var msg = err.message ? err.message : err; + callback(new Error('could not fetch affected tables or last updated time: ' + msg)); + return; + } -function handleAffectedTablesAndLastUpdatedTimeRows(err, rows, callback) { - if (err || rows.length === 0) { - var msg = err.message ? err.message : err; - callback(new Error('could not fetch affected tables or last updated time: ' + msg)); - return; - } + var result = rows[0]; - var result = rows[0]; + // This is an Array, so no need to split into parts + var tableNames = result.tablenames; - // This is an Array, so no need to split into parts - var tableNames = result.tablenames; + var lastUpdatedTime = result.max || 0; - var lastUpdatedTime = result.max || 0; - - callback(null, { - affectedTables: tableNames, - lastUpdatedTime: lastUpdatedTime * 1000 + callback(null, { + affectedTables: tableNames, + lastUpdatedTime: lastUpdatedTime * 1000 + }); }); -} +}; QueryTablesApi.prototype.getLastUpdatedTime = function (username, tableNames, callback) { if (!Array.isArray(tableNames) || tableNames.length === 0) { @@ -77,23 +71,21 @@ QueryTablesApi.prototype.getLastUpdatedTime = function (username, tableNames, ca '])' ].join(' '); - this.pgQueryRunner.run(username, query, handleLastUpdatedTimeRows, callback); + this.pgQueryRunner.run(username, query, function handleLastUpdatedTimeRows (err, rows) { + if (err) { + var msg = err.message ? err.message : err; + return callback(new Error('could not fetch affected tables or last updated time: ' + msg)); + } + // when the table has not updated_at means it hasn't been changed so a default last_updated is set + var lastUpdated = 0; + if (rows.length !== 0) { + lastUpdated = rows[0].max || 0; + } + + return callback(null, lastUpdated*1000); + }); }; -function handleLastUpdatedTimeRows(err, rows, callback) { - if (err) { - var msg = err.message ? err.message : err; - return callback(new Error('could not fetch affected tables or last updated time: ' + msg)); - } - // when the table has not updated_at means it hasn't been changed so a default last_updated is set - var lastUpdated = 0; - if (rows.length !== 0) { - lastUpdated = rows[0].max || 0; - } - - return callback(null, lastUpdated*1000); -} - function prepareSql(sql) { return sql .replace(affectedTableRegexCache.bbox, 'ST_MakeEnvelope(0,0,0,0)') diff --git a/lib/cartodb/api/tables_extent_api.js b/lib/cartodb/api/tables_extent_api.js index a6e45c2a..d4293ed7 100644 --- a/lib/cartodb/api/tables_extent_api.js +++ b/lib/cartodb/api/tables_extent_api.js @@ -35,19 +35,17 @@ TablesExtentApi.prototype.getBounds = function (username, tableNames, callback) "FROM ext" ].join(' '); - this.pgQueryRunner.run(username, query, handleBoundsResult, callback); + this.pgQueryRunner.run(username, query, function handleBoundsResult (err, rows) { + if (err) { + var msg = err.message ? err.message : err; + return callback(new Error('could not fetch source tables: ' + msg)); + } + var result = null; + if (rows.length > 0) { + result = { + bounds: rows[0] + }; + } + callback(null, result); + }); }; - -function handleBoundsResult(err, rows, callback) { - if (err) { - var msg = err.message ? err.message : err; - return callback(new Error('could not fetch source tables: ' + msg)); - } - var result = null; - if (rows.length > 0) { - result = { - bounds: rows[0] - }; - } - callback(null, result); -} diff --git a/lib/cartodb/backends/pg_query_runner.js b/lib/cartodb/backends/pg_query_runner.js index 0ba40c3e..bf57f166 100644 --- a/lib/cartodb/backends/pg_query_runner.js +++ b/lib/cartodb/backends/pg_query_runner.js @@ -8,8 +8,14 @@ function PgQueryRunner(pgConnection) { module.exports = PgQueryRunner; - -PgQueryRunner.prototype.run = function(username, query, queryHandler, callback) { +/** + * Runs `query` with `username`'s PostgreSQL role, callback receives error and rows array. + * + * @param {String} username + * @param {String} query + * @param {Function} callback function({Error}, {Array}) second argument is guaranteed to be an array + */ +PgQueryRunner.prototype.run = function(username, query, callback) { var self = this; var params = {}; @@ -33,8 +39,7 @@ PgQueryRunner.prototype.run = function(username, query, queryHandler, callback) }); psql.query(query, function(err, resultSet) { resultSet = resultSet || {}; - var rows = resultSet.rows || []; - queryHandler(err, rows, callback); + return callback(err, resultSet.rows || []); }); } ); diff --git a/test/acceptance/multilayer_server.js b/test/acceptance/multilayer_server.js index ab7686ef..e43070f1 100644 --- a/test/acceptance/multilayer_server.js +++ b/test/acceptance/multilayer_server.js @@ -310,8 +310,8 @@ describe('tests from old api translated to multilayer', function() { it("creates layergroup fails when postgresql queries fail to figure affected tables in query", function(done) { var runQueryFn = PgQueryRunner.prototype.run; - PgQueryRunner.prototype.run = function(username, query, queryHandler, callback) { - return queryHandler(new Error('fake error message'), [], callback); + PgQueryRunner.prototype.run = function(username, query, callback) { + return callback(new Error('fake error message'), []); }; var layergroup = singleLayergroupConfig('select * from gadm4', '#gadm4 { marker-fill: red; }'); @@ -365,8 +365,8 @@ describe('tests from old api translated to multilayer', function() { keysToDelete['user:localhost:mapviews:global'] = 5; var runQueryFn = PgQueryRunner.prototype.run; - PgQueryRunner.prototype.run = function(username, query, queryHandler, callback) { - return queryHandler(new Error('failed to query database for affected tables'), [], callback); + PgQueryRunner.prototype.run = function(username, query, callback) { + return callback(new Error('failed to query database for affected tables'), []); }; // reset internal cacheChannel cache From c664d5392c5cf04a923554517515f8a31c329554 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 30 Dec 2015 17:48:00 +0100 Subject: [PATCH 19/33] Adds some tests about how to use PgQueryRunner isolated --- test/integration/pg-query-runner.js | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 test/integration/pg-query-runner.js diff --git a/test/integration/pg-query-runner.js b/test/integration/pg-query-runner.js new file mode 100644 index 00000000..9cb9fcbe --- /dev/null +++ b/test/integration/pg-query-runner.js @@ -0,0 +1,46 @@ +require('../support/test_helper'); + +var assert = require('assert'); + +var RedisPool = require('redis-mpool'); +var cartodbRedis = require('cartodb-redis'); + +var PgConnection = require('../../lib/cartodb/backends/pg_connection'); +var PgQueryRunner = require('../../lib/cartodb/backends/pg_query_runner'); + + +describe('PgQueryRunner', function() { + + var queryRunner; + + before(function() { + var redisPool = new RedisPool(global.environment.redis); + var metadataBackend = cartodbRedis({pool: redisPool}); + var pgConnection = new PgConnection(metadataBackend); + queryRunner = new PgQueryRunner(pgConnection); + }); + + it('should work for happy case', function(done) { + var query = 'select cartodb_id from test_table limit 3'; + queryRunner.run('localhost', query, function(err, result) { + assert.ok(!err, err); + + assert.ok(Array.isArray(result)); + assert.equal(result.length, 3); + + done(); + }); + }); + + it('should receive rows array even on error', function(done) { + var query = 'select __error___ from test_table'; + queryRunner.run('localhost', query, function(err, result) { + assert.ok(err); + + assert.ok(Array.isArray(result)); + assert.equal(result.length, 0); + + done(); + }); + }); +}); From 74898e4261f22edb1b6cfff8a4a8f7c0ae161aa9 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 30 Dec 2015 17:48:24 +0100 Subject: [PATCH 20/33] Integration tests for QueryTablesApi Again this is more about how it would be possible to use it isolated. --- test/integration/query-tables-api.js | 55 ++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 test/integration/query-tables-api.js diff --git a/test/integration/query-tables-api.js b/test/integration/query-tables-api.js new file mode 100644 index 00000000..d05b1ed0 --- /dev/null +++ b/test/integration/query-tables-api.js @@ -0,0 +1,55 @@ +require('../support/test_helper'); + +var assert = require('assert'); + +var RedisPool = require('redis-mpool'); +var cartodbRedis = require('cartodb-redis'); + +var PgConnection = require('../../lib/cartodb/backends/pg_connection'); +var PgQueryRunner = require('../../lib/cartodb/backends/pg_query_runner'); +var QueryTablesApi = require('../../lib/cartodb/api/query_tables_api'); + + +describe('QueryTablesApi', function() { + + var queryTablesApi; + + before(function() { + var redisPool = new RedisPool(global.environment.redis); + var metadataBackend = cartodbRedis({pool: redisPool}); + var pgConnection = new PgConnection(metadataBackend); + var pgQueryRunner = new PgQueryRunner(pgConnection); + queryTablesApi = new QueryTablesApi(pgQueryRunner); + }); + + // Check test/support/sql/windshaft.test.sql to understand where the values come from. + + it('should return an object with affected tables array and last updated time', function(done) { + var query = 'select * from test_table'; + queryTablesApi.getAffectedTablesAndLastUpdatedTime('localhost', query, function(err, result) { + assert.ok(!err, err); + + assert.deepEqual(result, { + affectedTables: [ 'public.test_table' ], + lastUpdatedTime: 1234567890123 + }); + + done(); + }); + }); + + it('should work with private tables', function(done) { + var query = 'select * from test_table_private_1'; + queryTablesApi.getAffectedTablesAndLastUpdatedTime('localhost', query, function(err, result) { + assert.ok(!err, err); + + assert.deepEqual(result, { + affectedTables: [ 'public.test_table_private_1' ], + lastUpdatedTime: 1234567890123 + }); + + done(); + }); + }); + +}); From 6f7bbe4ff521c233432e54ee50a7793183302047 Mon Sep 17 00:00:00 2001 From: Paul Norman Date: Wed, 30 Dec 2015 17:19:41 -0800 Subject: [PATCH 21/33] Move install instructions to their own file --- INSTALL.md | 43 +++++++++++++++++++++++++++++++++++++++++++ README.md | 44 +++----------------------------------------- 2 files changed, 46 insertions(+), 41 deletions(-) create mode 100644 INSTALL.md diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 00000000..2c6ed15e --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,43 @@ +# Installing Windshaft-CartoDB # + +## Requirements ## +Make sure that you have the requirements needed. These are + +- Core + - Node.js >=0.8 + - npm >=1.2.1 <2.0.0 + - PostgreSQL >8.3.x, PostGIS >1.5.x + - Redis >2.4.0 (http://www.redis.io) + - Mapnik 2.0.1, 2.0.2, 2.1.0, 2.2.0, 2.3.0. See [Installing Mapnik](https://github.com/CartoDB/Windshaft#installing-mapnik). + - Windshaft: check [Windshaft dependencies and installation notes](https://github.com/CartoDB/Windshaft#dependencies) + - libcairo2-dev, libpango1.0-dev, libjpeg8-dev and libgif-dev for server side canvas support + +- For cache control (optional) + - CartoDB 0.9.5+ (for `CDB_QueryTables`) + - Varnish (http://www.varnish-cache.org) + +- For running the testsuite + - ImageMagick (http://www.imagemagick.org) + + +Dependencies installation example: + + ```shell + sudo add-apt-repository -y ppa:cartodb/cairo + sudo apt-get update + sudo apt-get install -y build-essential checkinstall pkg-config libcairo2-dev libjpeg8-dev libgif-dev + ``` + +## Build/install ## + +To fetch and build all node-based dependencies, run: + +``` +npm install +``` + +Note that the ```npm install``` step will populate the node_modules/ +directory with modules, some of which being compiled on demand. If you +happen to have startup errors you may need to force rebuilding those +modules. At any time just wipe out the node_modules/ directory and run +```npm install``` again. diff --git a/README.md b/README.md index 891050db..88d4b897 100644 --- a/README.md +++ b/README.md @@ -13,32 +13,9 @@ This is the [CartoDB Maps API](http://docs.cartodb.com/cartodb-platform/maps-api * provides a link to varnish high speed cache * provides a [template maps API](https://github.com/CartoDB/Windshaft-cartodb/blob/master/docs/Template-maps.md) -Requirements ------------- - - Core - - Node.js >=0.8 - - npm >=1.2.1 <2.0.0 - - PostgreSQL >8.3.x, PostGIS >1.5.x - - Redis >2.4.0 (http://www.redis.io) - - Mapnik 2.0.1, 2.0.2, 2.1.0, 2.2.0, 2.3.0. See [Installing Mapnik](https://github.com/CartoDB/Windshaft#installing-mapnik). - - Windshaft: check [Windshaft dependencies and installation notes](https://github.com/CartoDB/Windshaft#dependencies) - - libcairo2-dev, libpango1.0-dev, libjpeg8-dev and libgif-dev for server side canvas support - -- For cache control (optional) - - CartoDB 0.9.5+ (for `CDB_QueryTables`) - - Varnish (http://www.varnish-cache.org) - -- For running the testsuite - - ImageMagick (http://www.imagemagick.org) - -Dependencies installation example: - -```shell -sudo add-apt-repository -y ppa:cartodb/cairo -sudo apt-get update -sudo apt-get install -y build-essential checkinstall pkg-config libcairo2-dev libjpeg8-dev libgif-dev -``` - +Install +------- +See [INSTALL.md](INSTALL.md) for detailed installation instructions. Configure --------- @@ -49,21 +26,6 @@ see ```./configure --help``` to see available options. Look at lib/cartodb/server_options.js for more on config -Build/install -------------- - -To fetch and build all node-based dependencies, run: - -``` -npm install -``` - -Note that the ```npm install``` step will populate the node_modules/ -directory with modules, some of which being compiled on demand. If you -happen to have startup errors you may need to force rebuilding those -modules. At any time just wipe out the node_modules/ directory and run -```npm install``` again. - Upgrading --------- From 7ed96ef0bbddd1b99a361350d97ba4f834ae65e2 Mon Sep 17 00:00:00 2001 From: Paul Norman Date: Wed, 30 Dec 2015 23:37:12 -0800 Subject: [PATCH 22/33] Add a list of packages and postgres instructions --- INSTALL.md | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/INSTALL.md b/INSTALL.md index 2c6ed15e..cfb6cfc4 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -20,13 +20,27 @@ Make sure that you have the requirements needed. These are - ImageMagick (http://www.imagemagick.org) -Dependencies installation example: +On Ubuntu 14.04 the dependencies can be installed with - ```shell - sudo add-apt-repository -y ppa:cartodb/cairo - sudo apt-get update - sudo apt-get install -y build-essential checkinstall pkg-config libcairo2-dev libjpeg8-dev libgif-dev - ``` +```shell +sudo apt-get update +sudo apt-get install -y make g++ pkg-config git-core \ + libgif-dev libjpeg-dev libcairo2-dev \ + libhiredis-dev redis-server \ + nodejs nodejs-legacy npm \ + postgresql-9.3-postgis-2.1 postgresql-plpython-9.3 postgresql-server-dev-9.3 +``` + +On Ubuntu 12.04 the [cartodb/cairo PPA](https://launchpad.net/~cartodb/+archive/ubuntu/cairo) may be useful. + +## PostGIS setup ## + +A `template_postgis` database is expected. One can be set up with + +```shell +createdb --owner postgres --template template0 template_postgis +psql -d template_postgis -c 'CREATE EXTENSION postgis;' +``` ## Build/install ## From 67e921017c58a3c86d2851cfda6b411e51631e1f Mon Sep 17 00:00:00 2001 From: csobier Date: Wed, 6 Jan 2016 08:44:53 -0500 Subject: [PATCH 23/33] added limit amount regarding named maps --- docs/Map-API.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/Map-API.md b/docs/Map-API.md index 75f20301..2bb335e9 100644 --- a/docs/Map-API.md +++ b/docs/Map-API.md @@ -352,6 +352,8 @@ The main two differences compared to anonymous maps are: Template maps are persistent with no preset expiration. They can only be created or deleted by a CartoDB user with a valid API_KEY (see auth section). +**Note:** There is a limit of 4,096 named maps allowed per account. If you need to create more Named Maps, it is recommended to use templates. + ### Create #### Definition From 8203c878f41b61414618717b6ce4ef3632fecd54 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Tue, 12 Jan 2016 15:53:16 +0100 Subject: [PATCH 24/33] Send 409 error code when maximum number of templates limit is reached Closes #346 --- lib/cartodb/backends/template_maps.js | 6 +- test/integration/template-maps-limits.js | 78 ++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 test/integration/template-maps-limits.js diff --git a/lib/cartodb/backends/template_maps.js b/lib/cartodb/backends/template_maps.js index 680cfe3a..c30b964c 100644 --- a/lib/cartodb/backends/template_maps.js +++ b/lib/cartodb/backends/template_maps.js @@ -224,8 +224,10 @@ o.addTemplate = function(owner, template, callback) { function installTemplateIfDoesNotExist(err, numberOfTemplates) { assert.ifError(err); if ( limit && numberOfTemplates >= limit ) { - throw new Error("User '" + owner + "' reached limit on number of templates " + - "("+ numberOfTemplates + "/" + limit + ")"); + var limitReachedError = new Error("User '" + owner + "' reached limit on number of templates (" + + numberOfTemplates + "/" + limit + ")"); + limitReachedError.http_status = 409; + throw limitReachedError; } self._redisCmd('HSETNX', [ userTemplatesKey, templateName, JSON.stringify(template) ], this); }, diff --git a/test/integration/template-maps-limits.js b/test/integration/template-maps-limits.js new file mode 100644 index 00000000..12150c68 --- /dev/null +++ b/test/integration/template-maps-limits.js @@ -0,0 +1,78 @@ +require('../support/test_helper'); + +var assert = require('assert'); +var redis = require('redis'); +var RedisPool = require('redis-mpool'); +var TemplateMaps = require('../../lib/cartodb/backends/template_maps'); + + +describe('TemplateMaps limits', function() { + + var OWNER = 'username'; + var templateCounter = 0; + function templateUniqueName() { + return 'tpl_' + templateCounter++; + } + function createTemplate() { + return { + version: '0.0.1', + name: templateUniqueName(), + layergroup: { + layers: [ + { + type: 'plain', + options: { + color: 'blue' + } + } + ] + } + }; + } + + var redisClient = redis.createClient(global.environment.redis.port); + var redisPool = new RedisPool(global.environment.redis); + + afterEach(function(done) { + redisClient.del('map_tpl|' + OWNER, done); + }); + + it('should allow to create templates when there is no limit in options', function(done) { + var templateMaps = new TemplateMaps(redisPool); + + templateMaps.addTemplate(OWNER, createTemplate(), function(err, templateName, template) { + assert.ok(!err, err); + assert.ok(template); + + templateMaps.addTemplate(OWNER, createTemplate(), function(err, templateName, template) { + assert.ok(!err, err); + assert.ok(template); + done(); + }); + }); + }); + + it('should allow to create templates with limit in options', function(done) { + var templateMaps = new TemplateMaps(redisPool, {max_user_templates: 1}); + + templateMaps.addTemplate(OWNER, createTemplate(), function(err, templateName, template) { + assert.ok(!err, err); + assert.ok(template); + done(); + }); + }); + + it('should fail to create more templates than allowed by options', function(done) { + var templateMaps = new TemplateMaps(redisPool, {max_user_templates: 1}); + + templateMaps.addTemplate(OWNER, createTemplate(), function(err, templateName, template) { + assert.ok(!err, err); + assert.ok(template); + templateMaps.addTemplate(OWNER, createTemplate(), function(err) { + assert.ok(err); + assert.equal(err.http_status, 409); + done(); + }); + }); + }); +}); From 353919239d3434269904cbdb3d12efb69207161f Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 18:59:33 +0100 Subject: [PATCH 25/33] Attempt to use travis' container based builds --- .travis.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index bbfbe798..5e98dd8c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,11 @@ +sudo: false + addons: postgresql: "9.3" before_install: - sudo apt-get update - - sudo apt-get install -y pkg-config libcairo2-dev libjpeg8-dev libgif-dev - - sudo apt-get install postgresql-plpython-9.3 + - sudo apt-get install -y postgresql-plpython-9.3 pkg-config libcairo2-dev libjpeg8-dev libgif-dev - createdb template_postgis - psql -c "CREATE EXTENSION postgis" template_postgis From 8ea159e0a11cd739c1f881bd13627eb631d4ad51 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 19:14:58 +0100 Subject: [PATCH 26/33] Remove sudo calls --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 5e98dd8c..b9f817dd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,8 +4,8 @@ addons: postgresql: "9.3" before_install: - - sudo apt-get update - - sudo apt-get install -y postgresql-plpython-9.3 pkg-config libcairo2-dev libjpeg8-dev libgif-dev + - apt-get update + - apt-get install -y postgresql-plpython-9.3 pkg-config libcairo2-dev libjpeg8-dev libgif-dev - createdb template_postgis - psql -c "CREATE EXTENSION postgis" template_postgis From 74abee27004a5011dd1898a827a54157fa4b946d Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 19:23:30 +0100 Subject: [PATCH 27/33] Use apt addon instead of apt-get install --- .travis.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index b9f817dd..351cf755 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,10 +2,15 @@ sudo: false addons: postgresql: "9.3" + apt: + packages: + - postgresql-plpython-9.3 + - pkg-config + - libcairo2-dev + - libjpeg8-dev + - libgif-dev before_install: - - apt-get update - - apt-get install -y postgresql-plpython-9.3 pkg-config libcairo2-dev libjpeg8-dev libgif-dev - createdb template_postgis - psql -c "CREATE EXTENSION postgis" template_postgis From 553c64bd8bc687d7314a4388d65ce7c93474c94e Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 19:32:50 +0100 Subject: [PATCH 28/33] Create extension for plpython --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 351cf755..1fea4316 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,6 +13,7 @@ addons: before_install: - createdb template_postgis - psql -c "CREATE EXTENSION postgis" template_postgis + - psql -c "CREATE EXTENSION plpython" template_postgis env: - NPROCS=1 JOBS=1 PGUSER=postgres From 18278da4bbb9e84b856e12b05d94d2c8d0e8e73d Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 19:36:01 +0100 Subject: [PATCH 29/33] Create language instead of extension --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 1fea4316..9ac935ac 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ addons: before_install: - createdb template_postgis - psql -c "CREATE EXTENSION postgis" template_postgis - - psql -c "CREATE EXTENSION plpython" template_postgis + - psql -c "CREATE LANGUAGE plpythonu" template_postgis env: - NPROCS=1 JOBS=1 PGUSER=postgres From 04a2d1d33c795fe0264cafe02aa03ae4ff511db8 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 20:11:24 +0100 Subject: [PATCH 30/33] Remove postgresql-plpython-9.3 --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9ac935ac..9f133944 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,6 @@ addons: postgresql: "9.3" apt: packages: - - postgresql-plpython-9.3 - pkg-config - libcairo2-dev - libjpeg8-dev From 3780aed1b7509ab1d1ea7323db9da34d772a8929 Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 20:14:04 +0100 Subject: [PATCH 31/33] Check with no postgresql-plpython-9.3 at all --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9f133944..41b31179 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,6 @@ addons: before_install: - createdb template_postgis - psql -c "CREATE EXTENSION postgis" template_postgis - - psql -c "CREATE LANGUAGE plpythonu" template_postgis env: - NPROCS=1 JOBS=1 PGUSER=postgres From 19216eaa88b110eeb63dc3b59a54bfb46a41f59f Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 20:21:41 +0100 Subject: [PATCH 32/33] Use create language instead of extension --- test/support/prepare_db.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/support/prepare_db.sh b/test/support/prepare_db.sh index fd920e8d..ab9149a2 100755 --- a/test/support/prepare_db.sh +++ b/test/support/prepare_db.sh @@ -78,9 +78,9 @@ if test x"$PREPARE_PGSQL" = xyes; then sed "s/:TESTPASS/${TESTPASS}/" | psql -v ON_ERROR_STOP=1 ${TEST_DB} || exit 1 - psql -c "CREATE EXTENSION plpythonu;" ${TEST_DB} -# curl -L -s https://github.com/CartoDB/cartodb-postgresql/raw/cdb/scripts-available/CDB_QueryStatements.sql -o sql/CDB_QueryStatements.sql -# curl -L -s https://github.com/CartoDB/cartodb-postgresql/raw/cdb/scripts-available/CDB_QueryTables.sql -o sql/CDB_QueryTables.sql + psql -c "CREATE LANGUAGE plpythonu;" ${TEST_DB} + curl -L -s https://github.com/CartoDB/cartodb-postgresql/raw/cdb/scripts-available/CDB_QueryStatements.sql -o sql/CDB_QueryStatements.sql + curl -L -s https://github.com/CartoDB/cartodb-postgresql/raw/cdb/scripts-available/CDB_QueryTables.sql -o sql/CDB_QueryTables.sql cat sql/CDB_QueryStatements.sql sql/CDB_QueryTables.sql | psql -v ON_ERROR_STOP=1 ${TEST_DB} || exit 1 From 97d3bed1d2f5854ec3d14ff510a92e48a6b2719e Mon Sep 17 00:00:00 2001 From: Raul Ochoa Date: Wed, 13 Jan 2016 20:33:12 +0100 Subject: [PATCH 33/33] test with pg 9.4 --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 41b31179..671832f0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,10 @@ sudo: false addons: - postgresql: "9.3" + postgresql: "9.4" apt: packages: + - postgresql-plpython-9.4 - pkg-config - libcairo2-dev - libjpeg8-dev