What is the correct (or recommended) approach to identifying a layer "type" in Leaflet/Javascript?

I am able to successfully use layer instanceof, but that only works when you know the type at design time(which I expect is usually the case).

map.eachLayer(function(layer) {
    console.log('_leaflet_id=' + layer._leaflet_id + ' is layer type= '+ getLayerTypeName(layer));

function getLayerTypeName(layer)
    if (layer instanceof L.Marker){
        return 'Marker';
    else if (layer instanceof L.Tooltip){
        return 'Tooltip';
    else if (layer instanceof L.esri.DynamicMapLayer){
        return 'DynamicMapLayer';
    else if (layer instanceof L.esri.BasemapLayer){
        return 'BasemapLayer';
    else if (layer instanceof L.Layer){
        return 'Layer';
        return 'Unknown';

Is there a different approach I should be using?



This isn't really a Leaflet issue, but a general one with Javascript. And it specifically concerns when you want the objects's name. For comparisons, there are plenty of ways to do it safely (as in your example).

Javascript has no classes, so you can only really rely on


However, if you use minified code, the constructor names often changes (as they are minified as well), so they will not be legible.

Some libs add the object names as properties (Leaflet doesn't), but you rarely ever need them as text.

See https://stackoverflow.com/a/1249554 for a more detailed discussion.

Note that you should never use these names for anything in your code (comparison/identification) except straight (debug) output, as they are unreliable.

| improve this answer | |

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.