Advanced Interactive Web Mapping, Programming, and Design

In-class Excercises: APIs

Part 1: CartoDB's SQL API

  1. Continue using the CartoDB table and SQL queries from last class if you have them available.
  2. Create a URL in your text editor that uses CartoDB's SQL API to fetch data. It should be of this form:
    https://{account}.cartodb.com/api/v2/sql?q={sql}
    Where {account} is replaced with your CartoDB username and {sql} is replaced with an SQL query.
  3. Go to this URL using your browser.
  4. Select the entire response you get back (all the text that shows up in your browser) and copy it.
  5. Open your JavaScript console, type the following:
    response = JSON.parse('
    Paste the copied text, add ') to close the quotes and function call and hit [enter].
  6. Explore the response using the console. Type response, hit [enter] and see the results.
  7. The data is stored in the key rows. View the contents of this by entering response.rows in your console and pressing [enter].
  8. rows is an array. In the console, examine the first row.
  9. Can you find the data within the response's rows?

Part 2: Using CartoDB's SQL API in jQuery

Here we do the same as we did in Part 1, but entirely in JavaScript.

  1. Make an HTML page and load jQuery on it. The body can be empty.
  2. Use jQuery's $.getJSON() function to fetch the URL you created in Part 1.
  3. Log out some of the rows' contents using console.log().

Part 3: Adding data to a map

  1. Write an SQL query that selects some of the Airbnb listings from the table you have loaded in CartoDB.
  2. Test the query in CartoDB to ensure that it works.
  3. Using this jsbin as a starting point, use the CartoDB SQL API, jQuery, and Leaflet to display the results of your query on a map.

Part 4: Adding data to an element on a page

  1. Write an SQL query that selects the average, minimum, and maximum price of the Airbnb listings you have loaded in CartoDB.
  2. Test the SQL query in CartoDB to ensure that it works as expected.
  3. Using this jsbin as an example, put each of the values returned by the SQL API in their own span elements on your page.