0

I want to restrict the panning in leaflet to paths, preferrably more than one. The idea is that it is only possible to pan along roads, or a precalculated trajectory, and not freely across the map.

http://leafletjs.com/reference.html#map-options

maxBounds seems to restrict to a rectangular area only. Dynamically resetting the rectangle to keep users close to the path seems like a possibility but not a pretty one.

cyborgx7
  • 43
  • 4

1 Answers1

1

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:

iH8
  • 27,722
  • 4
  • 67
  • 76
  • That's the first thing I found, but not the thing I was looking for. If you zoom in a little bit on that example and then pan around, you can move the path off screen. This creates even more of a problem with paths that aren't just a straight line. What I want is that panning is restricted to diagonally along that line, keeping it in the center of the shown area of the map. – cyborgx7 Oct 09 '15 at 09:13