[GIS] How to hide other features that are not currently selected in leaflet

jqueryjsonleaflet

If I load a JSON file I essentially get to do functions for each feature :

   var highlight = {
       'color': '#149c14',
       'weight': 4,
       'opacity': 1
   };

 ` $.getJSON("/data/geojson/gen.json", function(data){
           var genlayer = L.geoJson(data,{
           style:function(feature){
               return {color:"red"};
           },
           onEachFeature:function(feature, layer){
               layer.on('click', function(e){
                    //do functions to selected feature
                    selectedFeature = e.target;
                    layer.setStyle(highlight);
               });
           }
      });
    roads.addLayer(genLayer);
   });`

I'm trying to figure out a way though how to focus on the selected feature by additionally and temporarily hiding other features that are not selected at the moment.

How can I approach this problem in leaflet?

Best Answer

You can register the click event onEachFeature as you are doing, but to hide other features it requires a bit more logic. I've added a 'highlight' variable, and two functions hideLayers() and showLayers() to handle this.

In the example, hide is called when you click a point and show is called when you click on the the map. The function takes the approach of looping through each layer, and if it is not highlighted then remove it from the map.

See the full codepen example http://codepen.io/owenjam/pen/JbOxZg

   onEachFeature: function (feature, layer) {
        layer.on('click', function (e) {
            this.setStyle(highlight);
            e.target.feature.properties.highlight = true;
            hideLayers();
        });
        map.on('click', function (e) {
            //having trouble with resetStyle, so just change it back
            layer.setStyle({
             'color': 'blue',
             'weight': 3,
             'opacity': 1
           });
          showLayers();
        });
    }

and the functions:

function hideLayers (){
  this.layer.eachLayer(function(layer){
    if(!layer.feature.properties.highlight){
      map.removeLayer(layer);
    }
  });
}

function showLayers (){
  this.layer.eachLayer(function(layer){
    layer.feature.properties.highlight = false;
    map.addLayer(layer);
  });
}

The simplest way to hide layers temporarily is to just remove them from the map and add them back when you need them again. As per mourners explanation here

Only one feature can be highlighted at a time, multiple selections and highlights are possible, it will just require a bit more code. Hopefully this gets you started.