D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
andyreagan
Full window
Github gist
Leaflet dynamic layer control
<!DOCTYPE html> <html> <head> <title>Layers Control Tutorial - Leaflet</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" /> --> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js" integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw==" crossorigin=""></script> <style> html, body { height: 100%; margin: 0; } #map { width: 600px; height: 400px; } </style> </head> <body> <button onclick='addLayer()' >Add</button> <button onclick='removeLayer()'>Remove</button> <div id='map'></div> <script> var cities; function addLayer() { console.log("Adding layer"); cities = L.layerGroup(); L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.').addTo(cities), L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.').addTo(cities), L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.').addTo(cities), L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.').addTo(cities); var overlays = { "Cities": cities }; map.addLayer(cities); // remove the current control panel map.removeControl(baseControl); // add one with the cities citiesControl = L.control.layers(baseLayers, overlays).addTo(map); } function removeLayer() { console.log("Removing layer"); map.removeLayer(cities); // now put the control back map.removeControl(citiesControl); baseControl.addTo(map); } var mbAttr = 'Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="https://mapbox.com">Mapbox</a>', mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw'; var grayscale = L.tileLayer(mbUrl, {id: 'mapbox.light', attribution: mbAttr}), streets = L.tileLayer(mbUrl, {id: 'mapbox.streets', attribution: mbAttr}); var map = L.map('map', { center: [39.73, -104.99], zoom: 10, layers: [grayscale] }); var baseLayers = { "Grayscale": grayscale, "Streets": streets }; var baseControl = L.control.layers(baseLayers).addTo(map); // make a global control variable for the control with the cities layer... var citiesControl; </script> </body> </html>
https://unpkg.com/leaflet@1.3.1/dist/leaflet.js