Can I prevent panning Leaflet map out of the world's edge?

Terion picture Terion · Mar 3, 2014 · Viewed 24.2k times · Source

Is there a way to limit panning out of the world's edge? On this picture, brown is the world, grey is emptiness. I want to make it impossible to pan like this.

out of this world

Answer

approxiblue picture approxiblue · Jul 21, 2015

Leaflet allows you to control how much the map resists being dragged out of bounds with the maxBoundsViscosity option (value: 0 to 1). Setting it to maximum disables dragging out of bounds entirely.

var map = new L.Map('map', {
  center: bounds.getCenter(),
  zoom: 5,
  layers: [osm],
  maxBounds: bounds,
  maxBoundsViscosity: 1.0
});

This feature is available in 1.0.0. The relevant pull request includes a working example:

var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  osm1 = L.tileLayer(osmUrl, {
    maxZoom: 18,
    attribution: osmAttrib
  }),
  osm2 = L.tileLayer(osmUrl, {
    maxZoom: 18,
    attribution: osmAttrib
  }),
  bounds = new L.LatLngBounds(new L.LatLng(49.5, -11.3), new L.LatLng(61.2, 2.5));

var map1 = new L.Map('map1', {
  center: bounds.getCenter(),
  zoom: 5,
  layers: [osm1],
  maxBounds: bounds,
  maxBoundsViscosity: 0.75
});

var map2 = new L.Map('map2', {
  center: bounds.getCenter(),
  zoom: 5,
  layers: [osm2],
  maxBounds: bounds,
  maxBoundsViscosity: 1.0
});

var latlngs = L.rectangle(bounds).getLatLngs();
L.polyline(latlngs[0].concat(latlngs[0][0])).addTo(map1);
L.polyline(latlngs[0].concat(latlngs[0][0])).addTo(map2);
html,
body,
#map {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>

<h1>Left: Bouncy maxBounds. Right: Not bouncy.</h1>

<div id="map1" style="float: left; width:45%; height: 80%;"></div>
<div id="map2" style="float: left; width:45%; height: 80%;"></div>