[GIS] hide unhide layers in leaflet

geojsonlayersleaflet

I want to hide some layers when I click in a layer and restore the visibility back after clicking out. I tried with this code but it doesn't work – here is also the plunker code – Hide show layers

var layerVisibility = {};

var piky2 = new L.geoJson(pol01).addTo(map);
var piky3 = new L.geoJson(pick1).addTo(map);
var piky4 = new L.geoJson(pick2).addTo(map);

var piky1 = new L.geoJson(pol00, {
  style: function(feature) {
    return {
      fillOpacity: 0.55,
      weight: 7,
      color: '#eff682'
    };
  },
  onEachFeature: function(feature, layer) {
    layer.on({
      'mousemove': function(e) {
        e.target.setStyle({
          weight: 7,
          color: 'red'
        });
      },
      'mouseout': function(e) {
        //reset hiden layer to be shown
        layerVisibility[L.Util.stamp(pol01)] = true;
        piky1.resetStyle(e.target);
      },
      'click': function(e) {
        piky1.bindPopup(feature.properties.Name);
        //Hide some layers 
        layerVisibility[L.Util.stamp(pol01)] = false;
      }
    });
  }
}).addTo(map);

Best Answer

To hide a feature you can give it an invisible color with rgba(0,0,0,0) (the last value is the transparency value, 1.0 = opaque, 0 = fully transparent).

var piky1=new L.geoJson(pol00,{
    style: function (feature) {
        return {
            fillOpacity: 0.55,
            weight: 7,
            color: '#eff682'
        };
    },
    onEachFeature: function (feature, layer) {
        layer.on({
            'click': function (e) {
                e.target.setStyle({
                    weight: 7,
                    color: 'rgba(0,0,0,0)'
                });
            }
        });
    }}).addTo(map); 

Making a feature visible again if a user clicks outside of it is a bit trickier since there's no blur event on Leaflet's layers. What you can do is listen for clicks on the map and reset all features then:

map.on('click', function(e){
  piky1.eachLayer(function (layer) {
    piky1.resetStyle(layer);
  });
});

Hiding individual markers it not currently supported, but should be coming in the future version 1.0 (see bug report). You can hide a marker's icon by providing an invisible icon with setIcon(), but you can not use setIcon() on eachLayer(). Instead, you can use Javascript .style properties (similar to CSS properties) on the icon to hide or show it.

// hide marker on click
layer.on('click', function(m){
    m.target._icon.style.display = 'none';
    m.target._shadow.style.display = 'none';
});

// show all markers again
piky3.eachLayer(function (layer) {
    layer._icon.style.display = 'block';
    layer._shadow.style.display = 'block';
});

Full code: http://plnkr.co/edit/rj1eF0ZhEpDGnwkz4oZr?p=preview