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!
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.
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.
####Bringing in your data layers For our Criminal States map, the code below does a few things.
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.
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.
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.
Please fill out the below form and we'll be in touch real soon.