1

In my Django app I have a leaflet map with two layers "active_event_layer" and "inactive_event_layer". I can select which layer I want to see in the top right menu. But when the page is loaded no layer is selected by default, so in order to see a layer I must selected it first. What I want to do is to set a layer by default, so, when the page is loaded the "Active events" layer is selected by default. I want to set the Active event layer selected as default

Here is my code:

 var active_event_collection = {{ active_events|geojsonfeature:"name"|safe }};
 var inactive_event_collection = {{ inactive_events|geojsonfeature:"name"|safe }};

  function onEachFeature(feature, layer) {
    layer.bindPopup(feature.properties.name);
  }

  function map_init(map, options) {

    var active_event_layer= L.geoJson(active_event_collection, {onEachFeature: onEachFeature})
    var inactive_event_layer = L.geoJson(inactive_event_collection, {onEachFeature: onEachFeature})

    var basemaps = {
            "Gray scale": L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
            }),
            Streets: L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
            })
        };

        var overlayMaps = {
            "Active events": active_event_layer,
            "Inactive events": inactive_event_layer,
          
        };
      
        var features = L.control.layers(basemaps, overlayMaps).addTo(map);
        map.fitBounds(active_event_layer.getBounds());
   
  }
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Ernesto Ruiz
  • 736
  • 9
  • 31
  • 1
    Add it to the map. – IvanSanchez Aug 16 '21 at 17:35
  • By doing active_event_layer.addTo(map); works !! Thank you If you prefer you can submit an answer so I can mark it as Correct answer – Ernesto Ruiz Aug 16 '21 at 18:19
  • Nah, that stuff is already explained in the Leaflet tutorials (https://leafletjs.com/examples/layers-control/). I'm of the opinion that if something is clear enough in the manuals/docs/examples, it doesn't need a SO Q&A. – IvanSanchez Aug 17 '21 at 19:07

0 Answers0