Control Leadlet Overlays
Adding several lays to leaflet and display the basic information of the layers on the map is very useful. Leaflet
provaided lots handy APIs.
This article talks about how to update the layers’ information according to users selection.
Add layers to leaflet
Base layer:1
2
3
4
5
6
7
8
9
10
11
12
13
14// OSM map
var OpenStreetMap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'
});
// Mapbox map
var Mapbox_light = L.tileLayer('https://api.mapbox.com/styles/v1/cherylzuo/cji2tjfdj10032sp4xfjd7nvp/tiles/256/{z}/{x}/{y}?access_token=pk.yourowntoken', {
attribution: '© <a href="https://www.mapbox.com/">Mapbox</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'
});
var baseLayers = {
"Open Street Map": OpenStreetMap,
"Light Map": Mapbox_light
};
In this example, Geojson is added as overlays (the geojson used in this case is polygons).
Overlay styles:1
2
3
4
5
6
7
8
9
10
11var transportationStyle = {
"color": "#2340b9",
"weight": 1,
"opacity": 0.01
};
var nature_resourceStyle = {
"color": "#60ee4c",
"weight": 1,
"opacity": 0.5
};
Geojson layers:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15//add geojson polygon to the map
var transportation = new L.geoJSON(transportation, {
style: transportationStyle,
// onEachFeature: layersOnEachFeature
});
//add geojson polygon to the map
var nature = new L.geoJSON(nature_resources, {
style: nature_resourceStyle
});
var overlays_geojson = {
"Transportation": transportation,
"Nature resources": nature
};
Add baselays and overlays to map
:1
2// add layer control to the map, overlays invisible by default
L.control.layers(baseLayers,overlays_geojson).addTo(map);
Add info box
When users click on overlays, the corresponding information will appear/disappear on the webpage.
1 | var info = L.control(); |
Custermize info box
When users click the overlay button, we need to know which layer(s) is checked. We need to add listeners on overlayadd
and overlayremove
. By comparing the added/removed layers with the overlay elements, we can know which layer is clicked.
1 | // list of on display overlays |