5

I need to close popups on an object, but I don't know whether it is a layer or a geoJSON (and hence a feature group). If the former, I can do layer.closePopup(), but if the latter, I have to do layer.eachLayer().closePopup() (I think).

How do I test whether an object in Leaflet is a layer or a group? I'm getting some joy with if (layer.childNodes), but it doesn't always seem to work, and I'd rather have a Leaflet solution than a DOM one, as I think it would be more reliable.

2

using javascript to test if the function is defined:

if (typeof layer.closePopup == 'function') {
    layer.closePopup()
} else {
    layer.eachLayer(function(layer) { layer.closePopup() })
}
1
  • Works perfectly. In lieu of a Leaflet API answer, I'm very happy to accept this method. Oct 1 '15 at 8:56
2

Use javascript's instanceof:

if (layer instanceof L.LayerGroup) {
    ...
}
0

L.LayerGroup can contain other LayerGroups, pretty confusing. I made this generic solution for recursively traversing a layergroup in my app ('vg.Map.' are just namespaces):

/*  vg.Map.recurseLayerGroup
    Run recursively through L.LayerGroup until contained layers are no
    longer instances of L.LayerGroup, then execute callback function.

    Parameters:
    o.layer - L.LayerGroup instance to examine.
    o.done - callback function to execute on non-layergroup instances.
      receives one argument, the layer instance.
*/
vg.Map.recurseLayerGroup = function(o){
  var o = o || {};
  o.done = typeof o.done === 'function' ? o.done : 
    function(lr){vg.log('console.Map.recurseLayerGroup done',lr);};
  var go = function(lr1){
    if(lr1 instanceof L.LayerGroup){
      // console.log('vg.Map.recurseLayerGroup instanceof true');
      lr1.eachLayer(function(lr2){ 
        go(lr2); 
      });
    } else {
      // console.log('vg.Map.recurseLayerGroup instanceof false');
      o.done(lr1);
    }
  };
  go(o.layer);
};

Then pass in appropriate callback function from elsewhere in the app:

  var lgDone = function(lr){
    lr instanceof L.Marker ? lr.setIcon(vg.Map.Icon.Default) :0;
  };
  myLayer instanceof L.LayerGroup ? vg.Map.recurseLayerGroup({layer:myLayer, done:lgDone}) :0;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.