Written by Santiago Giraldo on

Creating a Layer Selector: Crime in the U.S.A.

Core Tech

Layer Selector header

Making maps can be a challenge. Whether you’re just getting started with the CARTO Editor or you’re a seasoned geo-spatial developer using the CARTO Platform, The tools that CARTO offers allows for incredible versatility in how data is visualized, analyzed and made interactive. Just take a look at some of the awesome use-cases in our gallery!

In making complex maps, our JavaScript library - CARTO.js - makes it easy to work with to your data tables and maps stored in CartoDB. CartoDB.js allows you to connect to your stored visualizations, create new visualizations, add custom interaction, and query your raw data from a web browser. Check out this map of different crimes by the numbers is the United States built using both the editor and CARTO.js library:

Crime Map

One feature of the map above, and possibly the most requested functionality achieved through using our JavaScript library, is the ability to create a layer selector from your visualization layers in the editor. CARTO.js makes this easy by allowing you to access your map layers, stylings and data with a few simple lines of code and your vizjson.

Making a layer and legend selector using CARTO.js

Making the buttons

Layers

Once you have your layers organized in the CARTO editor, and finish setting up your coding environment, the first step in creating a layer selector is to create the buttons where the user can interact with the createSelector function on your visualization.

        <div id="cartocss" class="layer_selector">
            <p id="js-crime-selector">CRIME SELECTOR</p>
            <ul class="LayerSelector-list">
                <li data="0" class="vio">Total Violent Crime
                </li>
                <li data="1" class="vio">Aggravated Assault
                </li>
                <li data="2">Property Crime
                </li>
                <li data="3">Burglary
                </li>
                <li data="4">Motor Vehicle Theft
                </li>
                <li data="5" class="vio">Murder/Non-Negligibe Homicide
                </li>
                <li data="6">Larceny Theft
                </li>
                <li data="7">Robbery
                </li>
            </ul>
        </div>

The data attribute, which is essential for the layer selector, corresponds with the layer order in the editor. If you take a look at the image above and compare it to the HTML, you can see how these elements correlate.

The HTML buttons also contain a class attribute that corresponds with whether the crime is violent or not violent. This is used for toggling the legends, which are created as JavaScript objects with the default set to non-violent.

			var densityLegend = new cdb.geo.ui.Legend.Density({
         		title:   "<a href='http://www.fbi.gov/about-us/cjis/ucr/ucr'>Data From FBI Crime Reporting 2013</a>",
            	left: "Low", right: "High", colors: [ "#FFFFB2", "#FED976", "#FEB24C", "#FD8D3C", "#FC4E2A", "#E31A1C", "#B10026"  ]
            });
            $('#map').append(densityLegend.render().el);
            // Hide the legend for Violent crimes by default
            $(densityLegend.render().el).hide()
		    var densityLegendNon = new cdb.geo.ui.Legend.Density({
                title: "  <a href='http://www.fbi.gov/about-us/cjis/ucr/ucr'>Data From FBI Crime Reporting 2013</a>",
                left: "Low", right: "High", colors: [ "#FFFFCC", "#C7E9B4", "#7FCDBB", "#41B6C4", "#1D91C0", "#225EA8", "#0C2C84" ]
            });
            $('#map').append(densityLegendNon.render().el);

####Bringing in your data layers For our Criminal States map, the code below does a few things.

            cartodb.createLayer(map_object,'http://team.cartodb.com/api/v2/viz/5a9a49ce-b3a9-11e4-921d-0e9d821ea90d/viz.json')
                .addTo(map_object)
                .done(function(layer) {
                  $("li").on('click', function(e) {
                    var num = +$(e.target).attr('Data');
                    createSelector(layer,num,$(e.target).hasClass('vio'));
                  });
                })

First it brings in the vizjson and adds it to the map_object variable reproducing your visualization. It then identifies that the layers correspond with with the clickable list items in your HTML buttons using the data attribute as the num variable as the identifier. Lastly, it identifies that the createSelector function is determined by the layer in relationship to the data attribute (num) and whether the selected layer is a violet crime or not according to the class=”vio” attribute we set above.

Creating the selector functionality

The createSelector function brings in how all of the previously set up conditions work for the user. This function states that when when a particular layer is selected on click, that particular layer is made visible while the rest of the layers are hidden. For the violent variable, if the layer is violent, it shows the created densityLegend for violent crimes and hides the densityLegendNon which corresponds with non-violent crimes. If the layer is not violent, the inverse occurs.

            // Create layer selector
            function createSelector(layer,num,violent) {
             for (var i = 0; i < layer.getSubLayerCount(); i++) {
              if (i === num) {
                layer.getSubLayer(i).show();
              } else {
                layer.getSubLayer(i).hide();
              }
             }
             if (violent){
                $(densityLegendNon.render().el).hide()
                $(densityLegend.render().el).show()
             } else {
                $(densityLegend.render().el).hide()
                $(densityLegendNon.render().el).show()
             }
            }

The final product of all of these pieces together creates a beautiful and functional Criminal States Map!


We hope this blog post helped introduce some of the powerful possibilities of CARTO.js. Don’t forget to keep learning with our CARTO.js course in the Academy and check out our tutorials page for more cool examples of what’s possible with CARTO.

Happy mapping!

Don’t forget to share this post on Twitter, Facebook, and Linkedin!

Related Posts

Ready to optimize your territories with Location Intelligence?

Close circle icon

Contact us

Please fill out the below form and we'll be in touch real soon.