从地图中移除 carto 层

Remove carto layer from map

我可以按以下方式在第一次单击时向我的地图添加 carto 图层。但是,我不确定如何在第二次单击时或以类似切换的方式删除图层?

    $("#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
    }

layer.hide()

从地图中隐藏图层。

layer.show()

在地图中显示之前添加的图层。

layer.toggle() 切换层的可见性和 returns 指示新状态的布尔值(如果显示层则为 true,如果隐藏则为 false)

Documentation

我的解决方法如下。定义子层很重要:

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