Search code examples
javascriptleaflet

Leaflet - Custom Control Layer Button


I am kinda stumped on this. The code below works correctly to create a set of gridlines. I would like to set it up so that I can turn them on and off under the overlay/control layers box. How would I go about turning this code on and off using a check box in the control box?

Thank you!

//Grid lines

var hold = 0
for (let i = 0; i <17; i++) {

var pointA = map.unproject([hold, 0], map.getMaxZoom());
var pointB = map.unproject([hold, 8192], map.getMaxZoom());
var pointList = [pointA, pointB];
var firstpolyline = new L.Polyline(pointList, {
    color: 'grey',
    weight: 4,
    opacity: 0.8,
    smoothFactor: 1

});
firstpolyline.addTo(map);

var pointA = map.unproject([0, hold], map.getMaxZoom());
var pointB = map.unproject([8192, hold], map.getMaxZoom());
var pointList = [pointA, pointB];
var firstpolyline = new L.Polyline(pointList, {
    color: 'grey',
    weight: 4,
    opacity: 0.8,
    smoothFactor: 1

});
firstpolyline.addTo(map);

hold = hold + 512
}```

Solution

  • You can create a FeatureGroup and add to them the layers and then you can add the FeatureGroup to the LayersControl.

    var fg = L.featureGroup().addTo(map); // If you want to hide it initial remove .addTo(map)
    yourLayerControlVariable.addOverlay(fg);
    ...
    firstpolyline.addTo(fg);