Leaflet Map Layers – How to Define Displayed Layer on Leaflet Map

featureslayersleafletoverlay

I have 7 layers overlay on a base map, i need to define which layer is selected (active,displayed,shown) on the map.

var overlays = {
        "AL HOUDA Espaces_Verts": alhouda6_layer,
        "AL_HOUDA_imm": alhouda7_layer,
        "AL_HOUDA_villa": alhouda8_layer,
        "AL HOUDA_ECO": alhouda5_layer,
        "AL_HOUDA_EQUIP": alhouda4_layer,
        "AL_HOUDA_REC": alhouda3_layer,
        "AL_HOUDA_PARK": alhouda2_layer,
        "AL_HOUDA_200lOG": alhouda1_layer,
    };

L.control.layers(baseLayers,overlays).addTo(map);

For example when i select "AL_HOUDA_villa" and it's shown on the map i want to define that it's selected so i can show data just for this layer

enter image description here

Best Answer

It sounds like you want to designate just that overlay layer to be shown/active/displayed when you first load the map?

You just need to add the layer to the map:

var overlays = {
    "AL HOUDA Espaces_Verts": alhouda6_layer,
    "AL_HOUDA_imm": alhouda7_layer,
    "AL_HOUDA_villa": alhouda8_layer,
    "AL HOUDA_ECO": alhouda5_layer,
    "AL_HOUDA_EQUIP": alhouda4_layer,
    "AL_HOUDA_REC": alhouda3_layer,
    "AL_HOUDA_PARK": alhouda2_layer,
    "AL_HOUDA_200lOG": alhouda1_layer,
};

//this just adds the layers control to the map
L.control.layers(baseLayers,overlays).addTo(map);

//make the layer active. 
alhouda8_layer.addTo(map);

You can add that one line of code before or after defining your layers control, so this should work too:

//make the layer active. 
alhouda8_layer.addTo(map);

var overlays = {
    "AL HOUDA Espaces_Verts": alhouda6_layer,
    "AL_HOUDA_imm": alhouda7_layer,
    "AL_HOUDA_villa": alhouda8_layer,
    "AL HOUDA_ECO": alhouda5_layer,
    "AL_HOUDA_EQUIP": alhouda4_layer,
    "AL_HOUDA_REC": alhouda3_layer,
    "AL_HOUDA_PARK": alhouda2_layer,
    "AL_HOUDA_200lOG": alhouda1_layer,
};

//this just adds the layers control to the map
L.control.layers(baseLayers,overlays).addTo(map);

According to the documentation: "The layers control is smart enough to detect what layers we’ve already added and have corresponding checkboxes and radioboxes set." (http://leafletjs.com/examples/layers-control/)