In-class Exercise: JavaScript
Part 1: Embed a map with JavaScript
- Download this HTML and open it in a code editor (such as Brackets).
- Open the file in your browser.
- 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
and the mapid is the numbers and letters afterhttps://thenewschool.carto.com/u/brelsfoeagain/builder/79edb122-0374-11e7-b189-0e233c30368f/
/builder/
, in this case:https://thenewschool.carto.com/u/brelsfoeagain/builder/79edb122-0374-11e7-b189-0e233c30368f/
-
Replace the url for the map to one of your own maps. Currently this looks like
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/brelsfoeagain/api/v2/viz/79edb122-0374-11e7-b189-0e233c30368f/viz.json');
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
- Download this HTML and open it in a code editor (such as Brackets).
- Open the file in your browser.
- 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:
and in the JavaScript:<button class="public-water">public water</button>
$('.public-water').click(function () { watsanLayer.setSQL("SELECT * FROM watsan WHERE watsan = 'water_public'"); });
- 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>
- 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'"); });