Geocode your data and perform trade area analysis.

This component is still under support but it will not be further developed. We don’t recommend starting new projects with it as it will eventually become deprecated. Instead, learn more about our new APIs here

Introduction

The CARTO Data Services API offers a set of location based services that can be used to programatically customize subsets of data for your visualizations.

The contents described in this document are subject to CARTO’s Terms of Service

Authentication

Data Services API, like any other CARTO platform’s component, requires using an API Key. From your CARTO dashboard, click Your API keys from the avatar drop-down menu to view your uniquely generated API Key for managing data with CARTO Engine.

Your API Keys

Learn more about the basics of authorization, or dig into the details of Auth API, if you want to know more about this part of CARTO platform.

The examples in this documentation may include a placeholder for the API Key. Ensure that you modify any placeholder parameters with your own credentials.

Versioning

Data Services API uses Semantic Versioning. View our Github repository to find tags for each release.

Error handling

Most of the errors fired by the API are handled by the API itself. It triggers a CartoError every time an error happens.

A cartoError is an object containing a single message field with a string explaining the error.

Geocoding Functions

The geocoder functions allow you to match your data with geometries on your map. This geocoding service can be used programatically to geocode datasets via the CARTO SQL API. It is fed from Open Data and it serves geometries for countries, provinces, states, cities, postal codes, IP addresses and street addresses. CARTO provides functions for several different categories of geocoding through the Data Services API.

Warning: This service is subject to quota limitations and extra fees may apply. View the Quota Information section for details and recommendations about to quota consumption.

The following example displays how to geocode a single country:

1
https://{username}.carto.com/api/v2/sql?q=SELECT cdb_geocode_admin0_polygon('USA')&api_key={api_key}

In order to geocode an existent CARTO dataset, an SQL UPDATE statement must be used to populate the geometry column in the dataset with the results of the Data Services API. For example, if the column where you are storing the country names for each one of our rows is called country_column, run the following statement in order to geocode the dataset:

1
https://{username}.carto.com/api/v2/sql?q=UPDATE {tablename} SET the_geom = cdb_geocode_admin0_polygon('USA')&api_key={api_key}

Notice that you can make use of Postgres or PostGIS functions in your Data Services API requests, as the result is a geometry that can be handled by the system. For example, suppose you need to retrieve the centroid of a specific country, you can wrap the resulting geometry from the geocoder functions inside the PostGIS ST_Centroid function:

1
https://{username}.carto.com/api/v2/sql?q=UPDATE {tablename} SET the_geom = ST_Centroid(cdb_geocode_admin0_polygon('USA'))&api_key={api_key}

The following geocoding functions are available, grouped by categories.

Country Geocoder

This function geocodes your data into country border geometries. It recognizes the names of the different countries either by different synonyms (such as their English name or their endonym), or by ISO (ISO2 or ISO3) codes.

cdb_geocode_admin0polygon(_country_name text)

Geocodes the text name of a country into a country_name geometry, displayed as polygon data.

Arguments
Name Type Description
country_name text Name of the country
Returns

Geometry (polygon, EPSG 4326) or null

Example

Update the geometry of a table to geocode it

1
UPDATE {tablename} SET the_geom = cdb_geocode_admin0_polygon({country_column})

Insert a geocoded row into a table

1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_admin0_polygon('France')

Level-1 Administrative Regions Geocoder

This function geocodes your data into polygon geometries for Level 1, or NUTS-1, administrative divisions (or units) of countries. For example, a “state” in the United States, “départements” in France, or an autonomous community in Spain.

cdb_geocode_admin1polygon(_admin1_name text)

Geocodes the name of the province/state into a Level-1 administrative region, displayed as a polygon geometry.

Arguments
Name Type Description
admin1_name text Name of the province/state
Returns

Geometry (polygon, EPSG 4326) or null

Example
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_admin1_polygon({province_column})
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_admin1_polygon('Alicante')

cdb_geocode_admin1polygon(_admin1_name text, country_name text)

Geocodes the name of the province/state for a specified country into a Level-1 administrative region, displayed as a polygon geometry.

Arguments
Name Type Description
admin1_name text Name of the province/state
country_name text Name of the country in which the province/state is located
Returns

Geometry (polygon, EPSG 4326) or null

Example
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_admin1_polygon({province_column}, {country_column})
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_admin1_polygon('Alicante', 'Spain')

City Geocoder

This function geocodes your data into point geometries for names of cities. It is recommended to use geocoding functions that require more defined parameters — this returns more accurate results when several cities have the same name. If there are duplicate results for a city name, the city name with the highest population will be returned.

cdb_geocode_namedplace_point(city_name text)

Geocodes the text name of a city into a named place geometry, displayed as point data.

Arguments
Name Type Description
city_name text Name of the city
Returns

Geometry (point, EPSG 4326) or null

Example
Select
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_namedplace_point({city_column})
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_namedplace_point('Barcelona')

cdb_geocode_namedplace_point(city_name text, country_name text)

Geocodes the text name of a city for a specified country into a named place point geometry.

Arguments
Name Type Description
city_name text Name of the city
country_name text Name of the country in which the city is located
Returns

Geometry (point, EPSG 4326) or null

Example
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_namedplace_point({city_column}, 'Spain')
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_namedplace_point('Barcelona', 'Spain')

cdb_geocode_namedplace_point(city_name text, admin1_name text, country_name text)

Geocodes your data into a named place point geometry, containing the text name of a city, for a specified province/state and country. This is recommended for the most accurate geocoding of city data.

Arguments
Name Type Description
city_name text Name of the city
admin1_name text Name of the province/state in which the city is located
country_name text Name of the country in which the city is located
Returns

Geometry (point, EPSG 4326) or null

Example
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_namedplace_point({city_column}, {province_column}, 'USA')
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_namedplace_point('New York', 'New York', 'USA')

Postal Code Geocoder

These functions geocode your data into point, or polygon, geometries for postal codes. The postal code geocoder covers the United States, France, Australia and Canada; a request for a different country will return an empty response.

Note: For the USA, US Census Zip Code Tabulation Areas (ZCTA) are used to reference geocodes for USPS postal codes service areas. This is not a CARTO restriction, this is a US Government licensing protection of their zip code data source; which is not publicly available. Additionally, zip codes are considered service areas and are not actually geometric areas. As a solution, the US Census provides ZCTA data, which tabulates GIS postal codes for USPS locations by aggregating census blocks. For details about how ZCTAs are created, see ZIP Code™ Tabulation Areas (ZCTAs™). If you are geocoding data and your zip codes fail, ensure you are using ZCTAs for the postal code.

cdb_geocode_postalcode_polygon(postal_code text, country_name text)

Geocodes the postal code for a specified country into a polygon geometry.

Arguments
Name Type Description
postal_code text Postal code
country_name text Name of the country in which the postal code is located
Returns

Geometry (polygon, EPSG 4326) or null

Example
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_postalcode_polygon({postal_code_column}, 'USA')
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_postalcode_polygon('11211', 'USA')

cdb_geocode_postalcode_point(code text, country_name text)

Geocodes the postal code for a specified country into a point geometry.

Arguments
Name Type Description
postal_code text Postal code
country_name text Name of the country in which the postal code is located
Returns

Geometry (point, EPSG 4326) or null

Example
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_postalcode_point({postal_code_column}, 'USA')
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_postalcode_point('11211', 'USA')

IP Addresses Geocoder

This function geocodes your data into point geometries for IP addresses. This is useful if you are analyzing location based data, based on a set of user’s IP addresses.

cdb_geocode_ipaddress_point(ip_address text)

Geocodes a postal code from a specified country into an IP address, displayed as a point geometry.

Arguments
Name Type Description
ip_address text IPv4 or IPv6 address
Returns

Geometry (point, EPSG 4326) or null

Example
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_ipaddress_point('102.23.34.1')
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_ipaddress_point('102.23.34.1')

Street-Level Geocoder

These functions geocode your data into a point geometry for a street address. CARTO platform uses TomTom geocoding services by default as the service provider for street-level geocoding. Contact us if you have any specific questions or requirements about the location data service provider being used with your account.

This service is subject to quota limitations, and extra fees may apply. View the Quota information for details and recommendations about quota consumption.

cdb_geocode_street_point(search_text text, [city text], [state text], [country text])

Geocodes a complete address into a single street geometry, displayed as point data.

Arguments
Name Type Description
searchtext text searchtext contains free-form text containing address elements. You can specify the searchtext parameter by itself, or with other parameters, to narrow your search. For example, you can specify the state or country parameters, along with a free-form address in the searchtext field.
city text (Optional) Name of the city.
state text (Optional) Name of the state.
country text (Optional) Name of the country.
Returns

Geometry (point, EPSG 4326) or null

Example
Update the geometry of a table to geocode it
1
UPDATE {tablename} SET the_geom = cdb_geocode_street_point({street_name_column})
Insert a geocoded row into a table
1
INSERT INTO {tablename} (the_geom) SELECT cdb_geocode_street_point('651 Lombard Street', 'San Francisco', 'California', 'United States')

cdb_bulk_geocode_street_point (query text, street_column text, [city_column text], [state_column text], [country_column text], [batch_size integer])

Geocodes complete street addresses into point data. Similar to cdb_geocode_street_point, but using batch services and therefore allowing for several addresses to be geocoded in a single API call.

Arguments
Name Type Description
query text SQL query that returns the addresses to be geocoded. It must include a cartodb_id column and another column to get the free-form addresses from. Optionally, it may include other columns to fine-tune the geocoding, such as a city column, a state column and a country column.
street_column text Name of the free-form address column, must be present in the SQL query.
city_column text (Optional) Name of the city column, if present in the SQL query.
state_column text (Optional) Name of the state column, if present in the SQL query.
country_column text (Optional) Name of the country column, if present in the SQL query.
batch_size integer (Optional) Geocoding queries are sent in batches. Batch size can be configured, from 1 geocoding query per batch to a maximum value, limited by user quota or other limits. If not specified, it defaults to the maximum size available to the user, which is typically the best option, performance-wise.
Returns

Geocoding results are returned in an array. Each array element contains:

Name Type Description
cartodb_id integer cartodb_id from the original query.
the_geom Geometry (point, EPSG 4326) Point that corresponds to the most accurate match found for this particular address, or null if no match was found.
metadata JSON Information about the geocoding result, empty if no match was found.

The metadata JSON type includes the following attributes when geocoding was successful:

Name Type Description
precision text One of precise or interpolated.
relevance number Relevance factor, from 0 to 1, higher being more relevant.
match_type text Array with one of point_of_interest, country, state, county, locality, district, street, intersection, street_number, postal_code. Empty array if match type is unknown.
Example
Update the geometries of an entire table by geocoding all the rows based on a street address
1
WITH geocoding_results AS (SELECT cartodb_id, the_geom FROM cdb_bulk_geocode_street_point('SELECT cartodb_id, {address_column} from {tablename}', '{address_column}')) UPDATE {tablename} tn SET the_geom = geocoding_results.the_geom FROM geocoding_results WHERE tn.cartodb_id = geocoding_results.cartodb_id

Isoline Functions

Isolines are contoured lines that display equally calculated levels over a given surface area. This enables you to view polygon dimensions by forward or reverse measurements. Isoline functions are calculated as the intersection of areas from the origin point, measured by distance (isodistance) or time (isochrone). For example, the distance of a road from a sidewalk. Isoline services through CARTO are available by requesting a single function in the Data Services API.

This service is subject to quota limitations and extra fees may apply. View the Quota Information section for details and recommendations about to quota consumption.

You can use the isoline functions to retrieve, for example, isochrone lines from a certain location, specifying the mode and the ranges that will define each of the isolines. The following query calculates isolines for areas that are 5, 10 and 15 minutes (300, 600 and 900 seconds, respectively) away from the location by following a path defined by car routing and inserts them into a table.

1
https://{username}.carto.com/api/v2/sql?q=INSERT INTO {table} (the_geom) SELECT  the_geom FROM cdb_isodistance('POINT(-3.70568 40.42028)'::geometry, 'car', ARRAY[300, 600, 900]::integer[])&api_key={api_key}

The following functions provide an isoline generator service, based on time or distance. This service uses the isolines service defined for your account. The default service limits the usage of displayed polygons represented on top of Mapbox maps.

cdb_isodistance(source geometry, mode text, range integer[], [options text[]])

Displays a contoured line on a map, connecting geometries to a defined area, measured by an equal range of distance (in meters).

Note that not all the providers, for example TomTom, provide us a way to define the isoline limit in distance so we need to make some estimations. Due that estimations the produced isolines could not be 100% precise.

Arguments

Name Type Description Accepted values
source geometry Source point, in 4326 projection, which defines the start location.  
mode text Type of transport used to calculate the isolines. car or walk
range integer[] Range of the isoline, in meters.  
options text[] (Optional) Multiple options to add more capabilities to the analysis. See Optional isolines parameters for details.  
Returns
Name Type Description
center geometry Source point, in 4326 projection, which defines the start location.
data_range integer The range that belongs to the generated isoline.
the_geom geometry(MultiPolygon) MultiPolygon geometry of the generated isoline in the 4326 projection.
Examples
Calculate and insert isodistance polygons from a point into another table
1
INSERT INTO {table} (the_geom) SELECT  the_geom FROM cdb_isodistance('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300, 600, 900]::integer[])

or equivalently:

1
INSERT INTO {table} (the_geom) SELECT (cdb_isodistance('POINT(-3.70568 40.42028)'::geometry, 'walk', ARRAY[300, 600, 900]::integer[])).the_geom
Calculate and insert the generated isolines from points_table table to another table
1
INSERT INTO {table} (the_geom) SELECT (cdb_isodistance(the_geom, 'walk', string_to_array(distance, ',')::integer[])).the_geom FROM {points_table}

cdb_isochrone(source geometry, mode text, range integer[], [options text[]])

Displays a contoured line on a map, connecting geometries to a defined area, measured by an equal range of time (in seconds).

Arguments

This function uses the same parameters and information as the cdb_isodistance function, with the exception that the range is measured in seconds instead of meters.

Name Type Description Accepted values
source geometry Source point, in 4326 projection, which defines the start location.  
mode text Type of transport used to calculate the isolines. car or walk
range integer[] Range of the isoline, in seconds.  
options text[] (Optional) Multiple options to add more capabilities to the analysis. See Optional isolines parameters for details.  
Examples
Calculate and insert isochrone polygons from a point into another table
1
INSERT INTO {table} (the_geom) SELECT  the_geom FROM cdb_isochrone('POINT(-3.70568 40.42028)'::geometry, 'car', ARRAY[300, 900, 12000]::integer[], ARRAY['mode_traffic=enabled','quality=3']::text[])

or equivalently:

1
INSERT INTO {table} (the_geom) SELECT (cdb_isochrone('POINT(-3.70568 40.42028)'::geometry, 'car', ARRAY[300, 900, 12000]::integer[], ARRAY['mode_traffic=enabled','quality=3']::text[])).the_geom
Calculate and insert the generated isolines from points_table table into another table
1
INSERT INTO {table} (the_geom) SELECT (cdb_isochrone(the_geom, 'walk', string_to_array(time_distance, ',')::integer[])).the_geom FROM {points_table}

Optional isoline parameters

The optional value parameters must be passed using the format: option=value.

Name Type Description Accepted values
is_destination boolean If true, the source point is the destination instead of the starting location true or false. false by default
mode_type text Type of route calculation shortest or fastest. shortest by default
mode_traffic text Use traffic data to calculate the route enabled or disabled. disabled by default
resolution text Allows you to specify the level of detail needed for the isoline polygon. Unit is meters per pixel. Higher resolution may increase the response time of the service.  
maxpoints text Allows you to limit the amount of points in the returned isoline. If the isoline consists of multiple components, the sum of points from all components is considered. Each component will have at least two points. It is possible that more points than specified could be returned, in case when 2 * number of components is higher than the maxpoints value itself. Increasing the number of maxpoints may increase the response time of the service.  
quality text Allows you to reduce the quality of the isoline in favor of the response time. 1, 2, 3. Default value is 1, corresponding to the best quality option.

Routing Functions

Routing is the navigation from a defined start location to a defined end location. The calculated results are displayed as turn-by-turn directions on your map, based on the transportation mode that you specified. Routing services through CARTO are available by using the available functions in the Data Services API.

cdb_route_point_to_point(origin geometry(Point), destination geometry(Point), mode text, [options text[], units text])

Returns a route from origin to destination.

Arguments
Name Type Description Accepted values
origin geometry(Point) Origin point, in 4326 projection, which defines the start location.  
destination geometry(Point) Destination point, in 4326 projection, which defines the end location.  
mode text Type of transport used to calculate the routes. car, walk or bicycle
options text[] (Optional) Multiple options to add more capabilities to the analysis. See Optional routing parameters for details.  
units text (Optional) Unit used to represent the length of the route. kilometers, miles. By default is kilometers. This option is not supported by Mapbox provider
Returns
Name Type Description
duration integer Duration in seconds of the calculated route.
length real Length in the defined unit in the units field. meters by default .
the_geom geometry(LineString) LineString geometry of the calculated route in the 4326 projection.
Examples
Insert the values from the calculated route in your table
1
INSERT INTO <TABLE> (duration, length, the_geom) SELECT duration, length, shape FROM cdb_route_point_to_point('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car')
Update the geometry field with the calculated route shape
1
UPDATE <TABLE> SET the_geom = (SELECT shape FROM cdb_route_point_to_point('POINT(-3.70237112 40.41706163)'::geometry,'POINT(-3.69909883 40.41236875)'::geometry, 'car', ARRAY['mode_type=shortest']::text[]))

cdb_route_with_waypoints(waypoints geometry(Point)[], mode text, [options text[], units text])

Returns a route that goes from origin to destination and whose path travels through the defined locations.

Arguments
Name Type Description Accepted values
waypoints geometry(Point)[] Array of ordered points, in 4326 projection, which defines the origin point, one or more locations for the route path to travel through, and the destination. The first element of the array defines the origin and the last element the destination of the route.  
mode text Type of transport used to calculate the routes. car, walk or bicycle
options text[] (Optional) Multiple options to add more capabilities to the analysis. See Optional routing parameters for details.  
units text (Optional) Unit used to represent the length of the route. kilometers, miles. By default is kilometers. This option is not supported by Mapbox provider
Returns
Name Type Description
duration integer Duration in seconds of the calculated route.
length real Length in the defined unit in the units field. meters by default .
the_geom geometry(LineString) LineString geometry of the calculated route in the 4326 projection.

Note: A request to the function cdb_route_with_waypoints(waypoints geometry(Point)[], mode text, [options text[], units text]) with only two points in the geometry array are automatically defined as origin and destination. It is equivalent to performing the following request with these two locations as parameters: cdb_route_point_to_point(origin geometry(Point), destination geometry(Point), mode text, [options text[], units text]).

Examples
Insert the values from the calculated route in your table
1
INSERT INTO <TABLE> (duration, length, the_geom) SELECT duration, length, shape FROM cdb_route_with_waypoints(Array['POINT(-3.7109 40.4234)'::GEOMETRY, 'POINT(-3.7059 40.4203)'::geometry, 'POINT(-3.7046 40.4180)'::geometry]::geometry[], 'walk')
Update the geometry field with the calculated route shape
1
UPDATE <TABLE> SET the_geom = (SELECT shape FROM cdb_route_with_waypoints(Array['POINT(-3.7109 40.4234)'::GEOMETRY, 'POINT(-3.7059 40.4203)'::geometry, 'POINT(-3.7046 40.4180)'::geometry]::geometry[], 'car', ARRAY['mode_type=shortest']::text[]))

Optional routing parameters

The optional value parameters must be passed using the format: option=value. Not all are available for all the routing providers

Name Type Description Accepted values
mode_type text Type of route calculation shortest or fastest (this option only applies to the car transport mode)