leafletfitbounds

Leaflet - Zoom/Pan to Layer Extent when Toggling Layers


I am working on a bus route map, and have several routes that users can turn on and off. I would like to work out how to zoom/pan so that the chosen route (or routes) are fully on screen when chosen. (some are off screen with the initial zoom level).

Here's the magic so far:

var busRoute10 = L.geoJson([route10, busStop3, busStop4],{onEachFeature: onEachFeature});
var busRoute11 = L.geoJson([route11, busStop19, busStop16, busStop18, busStop22],{onEachFeature: onEachFeature});
var busRoute12 = L.geoJson([route12, busStop23, busStop42, busStop43, busStop15, busStop28, busStop27, busStop22, busStop16],{onEachFeature: onEachFeature});
var busRoute13 = L.geoJson([route13, busStop44, busStop31, busStop25, busStop26, busStop36],{onEachFeature: onEachFeature});


var baseLayers = {
"Route 10": busRoute10,
"Route 11": busRoute12,
"Route 12<hr>": busRoute14,
"Route 13": busRoute20,
};

L.control.layers(null, baseLayers, {collapsed: false}).setPosition ('topright').addTo(map);

I've tried multiple combinations of map.fitBounds, and just can't seem to get it.

Also, is there a way to add a title and subtitles to the control box? I'd like to have the contols look like:

Day
[]Route 10
[]Route 11
Night
[]Route 12... etc


Solution

  • You should attach a listener on map's "overlayadd" event. Then you can do your map.fitBounds() using the event.layer.getBounds(), since your layers are GeoJSON groups.

    As for organizing your layers in the Layers Control, it is not possible with the default control. But you can have a look at Leaflet plugins.