0

I am new to Carto.js and I don't understand how to work with it SQL.

How do I get bounds for this query?

const places = new carto.source.SQL(`SELECT * FROM someTable`);

I saw an example with cartoDb

sql.getBounds('select * from table').done(function(bounds) {
    map.fitBounds(bounds);
});

to get the bounds, but as I understand it is not the same.

  • The bounds is what you are looking for I think. In what way is it "not the same" same as what? – Jacob Mar 27 '18 at 15:06
4

You need to use the CARTO SQL API to retrieve that information applying a query with ST_EXTENT and parsing the response.

Here you have an example with simple code that you can use to get it running Get bounds with SQL API

Pseudocode for those steps:

const apiKey = 'YOUR_API_KEY';
const username = 'cartojs-test'
const tableName = 'someTable';

const places = new carto.source.SQL(`SELECT * ${tableName}`);

const boundsQuery = `SELECT ST_Extent(the_geom) as extent FROM ${tableName}`;
const boundsUrl = `https://${username}.carto.com/api/v2/sql?q=${query}&api_key=${apiKey}`

fetch(boundsUrl)
  .then(response => {
    return response.json()
  })
  .then(json => {
    const extent = json.rows[0].extent;
    const bounds = parseExtent(extent);
    map.fitBounds(
      [
        [bounds.south, bounds.west],
        [bounds.north, bounds.east]
      ]
    );
  });

This code uses ES6 and fetch so it'll work on modern browsers. You can use a regular ajax request for that using axios, jqueryor you preferred tool.

The code for the function parseExtentis the example Get bounds with SQL API. It only parses the extent response to a bounds object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.