The way to do this is indeed using the maxBounds
option or the setMaxBounds
method of your L.Map
instance. If for example you want to restrict the map's bounds to a polyline, you'll need the bounds of that polyline. You don't have to calculate that yourself, you can use the getBounds
method of the L.Polyline
class which returns a L.LatLngBounds
object. That object can be uses with the setMaxBounds
method of L.Map
:
var map = new L.Map('leaflet', {...});
var polyline = new L.Polyline([
[52.366667, 4.9],
[51.507222, -0.1275]
]).addTo(map);
// Get bounds
var bounds = polyline.getBounds();
// Set view to bounds
map.fitBounds(bounds);
// Restrict view to bounds
map.setMaxBounds(bounds);
Example on Plunker: http://plnkr.co/edit/jFw7mB?p=preview
The getBounds
method exists on all classes extended from L.Path
like L.MultiPolyline
, L.Polygon
, L.MultiPolygon
, L.Rectangle
, L.Circle
and L.CircleMarker
.
It also exists on layers L.FeatureGroup
and L.GeoJSON
which comes in very handy if you need to set the bounds to multiple features on your map. You contain them in a L.FeatureGroup
and then call the getBounds
method on the L.FeatureGroup
instance:
// Empty featuregroup
var featureGroup = new L.FeatureGroup().addTo(map);
// Add some features to featuregroup
var polyline1 = new L.Polyline([
[52.366667, 4.9],
[51.507222, -0.1275]
]).addTo(featureGroup);
var polyline2 = new L.Polyline([
[52.366667, 4.9],
[48.8567, 2.3508]
]).addTo(featureGroup);
var polyline3 = new L.Polyline([
[52.366667, 4.9],
[52.516667, 13.383333]
]).addTo(featureGroup);
// Get bounds of featuregroup
var bounds = featureGroup.getBounds();
// Set view to bounds
map.fitBounds(bounds);
// Restrict view to bounds
map.setMaxBounds(bounds);
Example on Plunker: http://plnkr.co/edit/yoax8c?p=preview
Reference: