javascriptjqueryd3.jscartodb

Remove carto layer from map


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
    }

Solution

  • 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();
            }