Advanced GIS

In-class Exercise: JavaScript

Part 1: Embed a map with JavaScript

  1. Download this HTML and open it in a code editor (such as Brackets).
  2. Open the file in your browser.
  3. Open a published Carto map you will embed on the page. Find the mapid by looking at the url when you have the map open. It should look something like
    https://thenewschool.carto.com/u/brelsfoeagain/builder/79edb122-0374-11e7-b189-0e233c30368f/
    and the mapid is the numbers and letters after /builder/, in this case:
    https://thenewschool.carto.com/u/brelsfoeagain/builder/79edb122-0374-11e7-b189-0e233c30368f/
  4. Replace the url for the map to one of your own maps. Currently this looks like
    cartodb.createVis('map', 'https://thenewschool.carto.com/u/brelsfoeagain/api/v2/viz/79edb122-0374-11e7-b189-0e233c30368f/viz.json');
    and you need to replace two parts of the url: the username and the mapid (which you found in step 3).
    cartodb.createVis('map', 'https://thenewschool.carto.com/u/{username}/api/v2/viz/{mapid}/viz.json');

Part 2: Change the options on a map

Continuing with your page from Part 1, change the initial center and zoom on your map using options in the documentation.

You currently have something like:

<script>
    $(document).ready(function () {
        cartodb.createVis('map', your_visualization_url);
    });
</script>

Add options like this:

<script>
    $(document).ready(function () {
        cartodb.createVis('map', your_visualization_url, {
            center_lat: 50,
            center_lon: -74,
        });
    });
</script>

(I'm only showing you how to do the center here, you should use the documentation to figure out how to do the zoom.)

Part 3: Filter a map layer with JavaScript

  1. Download this HTML and open it in a code editor (such as Brackets).
  2. Open the file in your browser.
  3. Right now the "public water" and "reset" buttons change the SQL of the layer when you click on them. Take a look at the HTML and JavaScript that we use for the "public water" button:
    <button class="public-water">public water</button>
    and in the JavaScript:
    $('.public-water').click(function () {
        watsanLayer.setSQL("SELECT * FROM watsan WHERE watsan = 'water_public'");
    });
  4. We want to add another button to filter the layer to just urban agriculture points. After the "public water" button add another button, this time for urban agriculture:
    <button class="urban-agriculture">urban agriculture</button>
  5. Reload the page. You should have a button that says "urban agriculture" but doesn't do anything when you click it. You need to add some JavaScript to make that part work. Add this in the JavaScript:
    $('.urban-agriculture').click(function () {
        watsanLayer.setSQL("SELECT * FROM watsan WHERE watsan = 'urban_agriculture'");
    });