-
Notifications
You must be signed in to change notification settings - Fork 1
Carto
Accessing data through the Carto API requires making an axios call or fetch with a "q" parameter that is a sql-like query. The good news is, it is well-documented, and pretty intuitive to use.
The fairly simple non-spatial example below shows building that single "q" parameter out of a set of variables, and calling fetch using just a string including the url + query:
let baseUrl = 'https://phl.carto.com/api/v2/sql?q=';
const eclipse_location_id = feature.properties.eclipse_location_id.replace(/\|/g, "', '");
const streetaddress = feature.properties.street_address;
const opaQuery = feature.properties.opa_account_num ? ` AND opa_account_num IN ('${ feature.properties.opa_account_num}')` : ``;
const pwd_parcel_id = feature.properties.pwd_parcel_id;
const addressId = feature.properties.li_address_key.replace(/\|/g, "', '");
const url = baseUrl += `SELECT * FROM PERMITS WHERE address = '${ streetaddress }' or addressobjectid IN ('${ addressId }') \
AND systemofrecord IN ('HANSEN') ${ opaQuery } \
UNION SELECT * FROM PERMITS WHERE addressobjectid IN ('${ eclipse_location_id }') OR parcel_id_num IN ( '${ pwd_parcel_id }' ) \
AND systemofrecord IN ('ECLIPSE')${ opaQuery }\
ORDER BY permittype`;
const response = await fetch(url);
Carto can handle spatial queries as well. The syntax is quite different from how ArcGIS Online does it. The dataset you are querying has a spatial field like "the_geom":
For instance, what if you want to find all of the features in a dataset that are less than 500 feet away from your current location. In this example, you would be the "feature" which has "geometry.coordinates" that equal your location. The where clause is a distance query ("ST_Distance"), comparing the dataset features and your coordinates:
const table = options.table;
const distances = options.distances || 250;
const distQuery = "ST_Distance(the_geom::geography, ST_SetSRID(ST_Point("
+ feature.geometry.coordinates[0]
+ "," + feature.geometry.coordinates[1]
+ "),4326)::geography)";
const latQuery = "ST_Y(the_geom)";
const lngQuery = "ST_X(the_geom)";
let select = "*, " + distQuery + 'as distance,' + latQuery + 'as lat, ' + lngQuery + 'as lng';
let params = {};
params['q'] = "select " + select + " from " + table + " where " + distQuery + " < " + distances;
const response = await axios.get('https://phl.carto.com/api/v2/sql?', { params })
There is a lot to learn about how the functions above ST_X, ST_Y, ST_Distance, ST_SetSRID, and ST_Point work. The Carto Documentation and googling "spatial sql" and finding Carto blog posts like this are the best way to learn.