Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save geog4046instructor/65f38124e3f56f11c9461b23335c0c92 to your computer and use it in GitHub Desktop.
Save geog4046instructor/65f38124e3f56f11c9461b23335c0c92 to your computer and use it in GitHub Desktop.
Leaflet - Control to show/hide a GeoJSON layer that has been added with AJAX through jQuery
/*
* This example shows how to add a layer list to a map where users can check and uncheck boxes to show and hide layers.
* The code below is combined with the code to add geojson to a map, since those two things are often used together.
* The code consists of five main parts:
* 1. Create the basemap(s) and layer(s)
* 2. Get geojson data and run a function to add it to a layer from step 1
* 3. Create the function that will be run in step 2
* 4. Create the list of layers that will appear in the control component
* 5. Create the control component
*/
/* 1 */
// create a basemap
let streets = L.tileLayer( 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' ).addTo( map )
// create an operational layer that is empty for now
let mylayer = L.layerGroup().addTo( map )
/* 2 */
// fill that layer with data from a geojson file
jQuery.getJSON( "https://example.com/layer.geojson", function( json ){
L.geoJSON( json, {
onEachFeature: addMyData,
})
})
/* 3 */
// This function is run for every feature found in the geojson file. It adds the feature to the empty layer we created above
function addMyData( feature, layer ){
mylayer.addLayer( layer )
// some other code can go here, like adding a popup with layer.bindPopup("Hello")
}
/* 4 */
// These options will appear in the control box that users click to show and hide layers
let basemapControl = {
"My Basemap": streets, // an option to select a basemap (makes more sense if you have multiple basemaps)
}
let layerControl = {
"My Layer": mylayer, // an option to show or hide the layer you created from geojson
}
/* 5 */
// Add the control component, a layer list with checkboxes for operational layers and radio buttons for basemaps
L.control.layers( basemapControl, layerControl ).addTo( map )
@lucahan
Copy link

lucahan commented Jun 29, 2018

thank you very much

@rene78
Copy link

rene78 commented Oct 27, 2018

@geog4046instructor, also thanks from my side! Exactly what I needed. Didn't really understand the leaflet documentation.

@pamcuellas
Copy link

Thank you, @geog4046instructor! This code helps me to solve the central issue in my project.

@hhsm95
Copy link

hhsm95 commented Apr 22, 2020

Thanks for sharing bro.

@wahidisna
Copy link

thank you for awesome snippet

@filipecardos0
Copy link

Thank you !

@vinh8lequang
Copy link

thank you!! is there any way to set the selection of the layers to be mutually exclusive instead of checkboxes like with the basemaps?

@Hamed-amn
Copy link

thanks for sharing
🙏

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