Last active
September 30, 2019 20:53
-
-
Save geog4046instructor/bb7df792661d12b4c236d84b96e260c5 to your computer and use it in GitHub Desktop.
Leaflet - Control to show/hide a GeoJSON layer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much! It really helps.