1

I am able to add a carto layer to my map on the first click as per below. However, I am unsure as to how to remove the layer on the second click, or in a toggle like way?

    $("#toggle").button(); 
    $("#toggle").on('click', firstClick)

    function firstClick() {
        $("#toggle").off('click').on('click', secondClick)
        var $this = $(this);
        $this.text('Heat');

        var cluster = cartodb.createLayer(map, {
                user_name : 'user_name',
                type : 'cartodb',
                sublayers : [{
                    sql : 'select * from lon_oa_residents_geocode_cluster',
                    cartocss : '#layer {marker-width: 7; marker-fill: ramp([cluster_no], (#bef4bf,  #005c02, #89ef8b, #64f567, #00f204, #009c03, #005c02,#000000, #004b01, #003801), quantiles); marker-fill-opacity: 1; marker-allow-overlap: true; marker-line-opacity: 0; }',
                    interactivity : 'cartodb_id'
                }]
            }).addTo(map); 
    }

    function secondClick() {
        $("#toggle").off('click').on('click', firstClick)
        var $this = $(this);
        $this.text('Map');      
        //insert code here to remove the cluster layer
    }
James
  • 307
  • 8
  • 22

2 Answers2

1

layer.hide()

Hides the layer from the map.

layer.show()

Shows the layer in the map if it was previously added.

layer.toggle() Toggles the visibility of the layer and returns a boolean that indicates the new status (true if the layer is shown, false if it is hidden)

Documentation

standby954
  • 209
  • 1
  • 7
0

My solution is as followed. Important to define the sublayer:

function firstClick() {
        //alert("First Clicked");
        $("#toggle").off('click').on('click', secondClick)
        var $this = $(this);
        $this.text('Density');

        var cluster = cartodb.createLayer(map, {
                user_name : 'user_name',
                type : 'cartodb',
                sublayers : [{
                    sql : 'select * from lon_oa_residents_geocode_cluster',
                    cartocss : '#layer {marker-width: 7; marker-fill: ramp([cluster_no], (#bef4bf,  #005c02, #89ef8b, #64f567, #00f204, #009c03, #005c02,#000000, #004b01, #003801), quantiles); marker-fill-opacity: 1; marker-allow-overlap: true; marker-line-opacity: 0; }',
                    interactivity : 'cartodb_id'
                }]
            }).addTo(map, 0).done(function (layer) {
                layer0 = layer; 
            });

        }

function secondClick() {
        $("#toggle").off('click').on('click', firstClick)           
            layer0.hide();
        }
James
  • 307
  • 8
  • 22