Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Leaflet Overlay Off in the Layer Control

Could someone help me to figure out how to set a leaflet overlay OFF by default when adding it to the map, please? For instance, setting the CITIES layer OFF on the map, as shown in the code below. The point is to have only the STATES layer ON and the CITIES OFF by default.

var baseMaps = {
    "Grayscale": grayscale, 
    "Streets": streets
};

var overlayMaps = {
    "Cities": cities, // Need to set OFF over the map
    "States": states  // Need to set ON  over the map
};

L.control.layers(baseMaps, overlayMaps).addTo(map);
like image 266
HelpOverFlow Avatar asked Sep 04 '17 21:09

HelpOverFlow


People also ask

How do you delete a layer on a map in Leaflet?

map. removeLayer(EPSLayer); map. removeLayer(TopoLayer); Depending on the layer you want to remove.

What is a layer in Leaflet?

In Leaflet, a “layer” is anything that moves around when the map is moved around. Before seeing how to create them from scratch, it's easier to explain how to do simple extensions.


1 Answers

You should not add it to the map in the first place. Somewhere before that code you posted you initialize the cities layer and add it to the map. Otherwise it wouldn't be on the map. For example:

var cities = new L.GeoJSON(...);
cities.addTo(map);

//Or

var cities = new L.GeoJSON(...);
map.addLayer(cities); 

Now when you add that to your layer control it's checkbox is automaticly checked by the control because it's already added to your map.

Example added after comment for clarification. Here is one layergroup added to the map and the other is not. Both are added to the layer control. Only the one that is added to the map is checked in the control:

var map = new L.Map('leaflet', {
    center: [0, 0],
    zoom: 0,
    layers: [
        new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
        })
    ]
});

// LAYERGROUP WITH ADD TO MAP
var layerGroup1 = new L.LayerGroup([
    new L.Marker([25, 25])
]).addTo(map);

// LAYERGROUP WITHOUT ADD TO MAP
var layerGroup2 = new L.LayerGroup([
    new L.Marker([-25, -25])
]);

var layerControl = new L.Control.Layers(null, {
    'Group 1': layerGroup1,
    'Group 2': layerGroup2
}).addTo(map);
body {
    margin: 0;
}

html, body, #leaflet {
    height: 100%;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Leaflet 1.0.3</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link type="text/css" rel="stylesheet" href="//unpkg.com/[email protected]/dist/leaflet.css" />
  </head>
  <body>
    <div id="leaflet"></div>
    <script type="application/javascript" src="//unpkg.com/[email protected]/dist/leaflet.js"></script>
  </body>
</html>
like image 114
iH8 Avatar answered Sep 22 '22 08:09

iH8