Search code examples
javascriptjqueryleaflettopojson

Retrieving removed TOPOJSON polygon on clicking a new one


I am trying to create an interactive map using leaflet and topojson layer. I want to do the following:

1- When one clicks a certain topojson polygon, it should remove.

2- When one clicks the other polygon, it should remove and the previously clicked polygon should be added back.

So basically there can only be one polygon absent at max at all times. Here's the code block for the map:

function addRegions(map) {
    var regionLayer = new L.TopoJSON();
    $.getJSON('map-developmentregions.topo.json').done(addRegionData);

    function addRegionData(topoData){
        regionLayer.addData(topoData);
        regionLayer.addTo(map);
        regionLayer.eachLayer(handleLayer);
    }

    function handleLayer(layer) {  
        layer.setStyle({
            fillColor : getColor(getNewsCount(layer.feature.properties.REGION)),
            weight: 2,
            opacity: 1,
            color: 'white',
            fillOpacity: 1
        });

        layer.on({
            mouseover : enterLayer,
            mouseout: leaveLayer,
            click: clickAction
        });
    }

    //Here's  the code for clickAction... this is where I suppose the code should be placed

    function clickAction(e) {
        var layer = e.target;
        map.removeLayer(layer);
    }
}

So far, this code allows me to click on the topojson polygon to remove it, but I cannot think of how to retrieve previously removed polygon, once the other polygon is clicked.

I think I should compare each polygon with the total number of polygons and add the missing polygon before removing the currently clicked polygon, but I am not able to execute that.

Please help. Thanks


Solution

  • In your clickAction() function, iterate over your data layer and add each feature to map. Once it finished, then remove the current feature.

    So, your click function would become

    function clickAction(e) {
        regionLayer.eachLayer(function(layer){
            map.addLayer(layer)
        });
        var layer = e.target;
        map.removeLayer(layer);
    }
    

    Note: Make it sure to change your variable regionLayer scope to a global variable, so as to make it accessible inside your click function.