Atlaslog
Atlaslog / Examples / OpenLayers / Extent Fit
OpenLayers · Runnable Example

Extent Fit

Runnable OpenLayers example: Extent Fit. 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 OpenLayers examples
/demos/openlayers-extent-fit.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-extent-fit.html
<!--
  示例:范围适配
  要点:view.fit(extent, {padding, duration}) 适配范围,虚线矩形标出目标区域
  依赖:OpenLayers 10.3.1 · 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/ol@10.3.1/ol.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;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar button{padding:3px 9px;border:1px solid #cfd4dc;border-radius:4px;
              background:#fff;cursor:pointer;font-size:12px}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <button id="fitDc">适配东城</button>
  <button id="fitAll">适配全城</button>
  <label><input type="checkbox" id="pad"> 加大内边距</label>
  <span id="info">—</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
  'use strict';

  if (typeof ol === 'undefined') {
    document.getElementById('map').innerHTML =
      '<div style="padding:20px;color:#b42318">OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  var fromLonLat = ol.proj.fromLonLat;

  var areas = {
    dongcheng: { min: [116.390, 39.890], max: [116.440, 39.940], name: '东城' },
    xicheng: { min: [116.340, 39.895], max: [116.395, 39.935], name: '西城' },
    chaoyang: { min: [116.430, 39.900], max: [116.500, 39.960], name: '朝阳' }
  };

  var features = Object.keys(areas).map(function (key) {
    var a = areas[key];
    var p1 = fromLonLat(a.min);
    var p2 = fromLonLat(a.max);
    var ring = [[p1[0], p1[1]], [p2[0], p1[1]], [p2[0], p2[1]], [p1[0], p2[1]], [p1[0], p1[1]]];
    return new ol.Feature({
      geometry: new ol.geom.Polygon([ring]),
      name: a.name
    });
  });

  var layer = new ol.layer.Vector({
    source: new ol.source.Vector({ features: features }),
    style: new ol.style.Style({
      fill: new ol.style.Fill({ color: 'rgba(194, 65, 12, 0.08)' }),
      stroke: new ol.style.Stroke({ color: '#c2410c', width: 2, lineDash: [8, 6] }),
      text: new ol.style.Text({
        font: '600 12px sans-serif',
        fill: new ol.style.Fill({ color: '#c2410c' }),
        stroke: new ol.style.Stroke({ color: '#ffffff', width: 3 })
      })
    })
  });

  layer.setStyle(function (feature) {
    return new ol.style.Style({
      fill: new ol.style.Fill({ color: 'rgba(194, 65, 12, 0.08)' }),
      stroke: new ol.style.Stroke({ color: '#c2410c', width: 2, lineDash: [8, 6] }),
      text: new ol.style.Text({
        text: feature.get('name'),
        font: '600 12px sans-serif',
        fill: new ol.style.Fill({ color: '#c2410c' }),
        stroke: new ol.style.Stroke({ color: '#ffffff', width: 3 })
      })
    });
  });

  var view = new ol.View({
    center: fromLonLat([116.410, 39.920]),
    zoom: 11,
    minZoom: 8,
    maxZoom: 18
  });

  new ol.Map({
    target: 'map',
    layers: [new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) }), layer],
    view: view,
    controls: ol.control.defaults.defaults({ attribution: false })
  });

  var pad = document.getElementById('pad');
  var info = document.getElementById('info');

  function currentPadding() {
    return pad.checked ? [80, 80, 80, 80] : [20, 20, 20, 20];
  }

  function fitExtent(extent, label) {
    view.fit(extent, {
      padding: currentPadding(),
      duration: 600,
      maxZoom: 16
    });
    info.textContent = '适配范围:' + label;
  }

  document.getElementById('fitDc').addEventListener('click', function () {
    var a = areas.dongcheng;
    fitExtent(ol.proj.transformExtent(
      [a.min[0], a.min[1], a.max[0], a.max[1]], 'EPSG:4326', 'EPSG:3857'), a.name);
  });

  document.getElementById('fitAll').addEventListener('click', function () {
    var extent = null;
    Object.keys(areas).forEach(function (key) {
      var e = ol.proj.transformExtent(
        [areas[key].min[0], areas[key].min[1], areas[key].max[0], areas[key].max[1]],
        'EPSG:4326', 'EPSG:3857');
      extent = extent ? ol.extent.extend(extent, e) : e;
    });
    fitExtent(extent, '全城');
  });
})();
</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 OpenLayers examples

OpenLayers · EXAMPLEExtent Interaction OpenLayers · EXAMPLEExternal Map OpenLayers · EXAMPLEFeature Animation