Skip to content

Instantly share code, notes, and snippets.

@geog4046instructor
Last active September 30, 2019 20:53
Show Gist options
  • Save geog4046instructor/bb7df792661d12b4c236d84b96e260c5 to your computer and use it in GitHub Desktop.
Save geog4046instructor/bb7df792661d12b4c236d84b96e260c5 to your computer and use it in GitHub Desktop.
Leaflet - Control to show/hide a GeoJSON layer
/*
* This example shows how to add a layer list to a map where users can check and
* and uncheck a box to show and hide a GeoJSON layer. This snippet assumes
* the map (map), basemap (streets), and GeoJSON (myLayerData) have already been
* declared.
*/
// create an operational layer that is empty for now
let myLayer = L.layerGroup().addTo(map)
// add all of the GeoJSON data to the empty layer we created
function addMyData (feature, layer) {
myLayer.addLayer(layer)
// some other code can go here, like adding a popup with layer.bindPopup("Hello")
}
// create an options object that specifies which function to call on each feature
let myLayerOptions = {
onEachFeature: addMyData
}
// create the GeoJSON layer from myLayerData
L.geoJSON(myLayerData, myLayerOptions).addTo(map)
// an object containing a list of basemaps (makes more sense to use with multiple basemaps)
let basemaps = {
'My Basemap': streets // replace streets with your basemap object, not shown in this snippet
}
// an object containing a list of operation layers
let layers = {
'My Layer': myLayer
}
L.control.layers(basemaps, layers).addTo(map)
@codyfet
Copy link

codyfet commented Sep 30, 2019

Thank you very much! It really helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment