Atlaslog
Atlaslog / Examples / Leaflet / Max Bounds
Leaflet · Runnable Example

Max Bounds

Runnable Leaflet example: Max Bounds. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All Leaflet examples
/demos/leaflet-max-bounds.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/leaflet-max-bounds.html
<!--
  示例:边界限制
  要点:maxBounds 与 maxBoundsViscosity、setMaxBounds 运行时开关、越界飞行的钳制效果
  依赖:Leaflet 1.9.4 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>边界限制</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:8px;align-items:center;flex-wrap:wrap;font-size:12px;color:#58606e}
  .bar button{font:inherit;font-size:12px;padding:4px 10px;border-radius:4px;cursor:pointer;
       border:1px solid #ccd1d9;background:#fff;color:#16181d}
  .bar button:hover{background:#eef0f3}
  .bar button.on{background:#1f5fd0;border-color:#1f5fd0;color:#fff}
  .bar b{color:#16181d;font-weight:600;font-variant-numeric:tabular-nums}
  #map{flex:1 1 auto;min-height:0;background:#edf0f4}
</style>
</head>
<body>
<div class="bar">
  <button id="limit" class="on">限制:开</button>
  <button id="fly">飞到上海</button>
  <button id="fit">回到北京</button>
  <span>中心 <b id="center">—</b></span>
  <span id="state">拖动时会停在虚线边界上</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
(function () {
  'use strict';

  var BOUNDS = L.latLngBounds([[39.850, 116.280], [39.970, 116.520]]);

  var map = L.map('map', {
    center: [39.907359, 116.391263],
    zoom: 12,
    minZoom: 10,
    maxZoom: 15,
    maxBounds: BOUNDS,
    /* 0 松手立刻回弹,1 完全拖不出去;中间值拖起来有阻力 */
    maxBoundsViscosity: 0.9
  });

  L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
    maxZoom: 19,
    attribution: 'Tiles © Esri'
  }).addTo(map);

  L.rectangle(BOUNDS, {
    color: '#c2410c',
    weight: 2,
    dashArray: '8 6',
    fill: false,
    interactive: false
  }).addTo(map);

  L.marker(BOUNDS.getCenter(), {
    icon: L.divIcon({
      className: '',
      html: '<div style="width:12px;height:12px;border-radius:50%;background:#c2410c;border:2px solid #fff"></div>',
      iconSize: [12, 12],
      iconAnchor: [6, 6]
    })
  }).addTo(map).bindTooltip('允许范围', { direction: 'top' });

  var centerEl = document.getElementById('center');
  var stateEl = document.getElementById('state');
  var limitBtn = document.getElementById('limit');

  function nearEdge(ll) {
    var pad = 0.004;
    var sw = BOUNDS.getSouthWest();
    var ne = BOUNDS.getNorthEast();
    return ll.lat <= sw.lat + pad || ll.lat >= ne.lat - pad ||
           ll.lng <= sw.lng + pad || ll.lng >= ne.lng - pad;
  }

  function refresh() {
    var c = map.getCenter();
    centerEl.textContent = c.lat.toFixed(4) + ', ' + c.lng.toFixed(4);

    if (!map.options.maxBounds) {
      stateEl.textContent = '限制已关闭,可以自由移动到任意区域';
    } else if (nearEdge(c)) {
      stateEl.textContent = '已贴住边界,无法继续向外拖';
    } else {
      stateEl.textContent = '范围内自由拖动,虚线外不可达';
    }
  }

  map.on('moveend zoomend', refresh);
  refresh();

  var limited = true;
  limitBtn.addEventListener('click', function () {
    limited = !limited;
    /* 传 null 即取消限制,恢复后重新套用同一个 bounds */
    map.setMaxBounds(limited ? BOUNDS : null);
    limitBtn.textContent = '限制:' + (limited ? '开' : '关');
    limitBtn.classList.toggle('on', limited);
    refresh();
  });

  document.getElementById('fly').addEventListener('click', function () {
    /* 关闭限制时会真的飞到上海;开启时 flyTo 会越界,moveend 后立刻被校正回边界 */
    map.flyTo([31.2304, 121.4737], 12, { duration: 1.2 });
  });

  document.getElementById('fit').addEventListener('click', function () {
    map.flyToBounds(BOUNDS, { padding: [30, 30], duration: 0.8 });
  });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More Leaflet examples

Leaflet · EXAMPLEMeasure Leaflet · EXAMPLEMinimap Leaflet · EXAMPLEOffline Tile