Last active
July 9, 2024 09:11
-
-
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 file contains 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 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 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you!! is there any way to set the selection of the layers to be mutually exclusive instead of checkboxes like with the basemaps?