Atlaslog
Atlaslog / Examples / OpenLayers / Vector Esri Edit
OpenLayers · Runnable Example

Vector Esri Edit

Runnable OpenLayers example: Vector Esri Edit. 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-vector-esri-edit.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-vector-esri-edit.html
<!--
  示例:可编辑的要素服务 — OpenLayers vector-esri-edit
  核心逻辑:Draw / Modify / Snap / Select 四个交互作用在同一 Vector 源上,实现增改删
  依赖: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{font:inherit;padding:3px 9px;border:1px solid #ccd2da;background:#fff;
       border-radius:3px;cursor:pointer;color:#2b3140}
  .bar button.on{background:#1f5fd0;border-color:#1f5fd0;color:#fff}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <button data-mode="point">画点</button>
  <button data-mode="line">画线</button>
  <button data-mode="polygon">画面</button>
  <button data-mode="modify">编辑顶点</button>
  <button data-mode="delete">删除要素</button>
  <button data-mode="none" class="on">浏览</button>
  <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 infoEl = document.getElementById('info');

  /* 初始数据:与要素服务返回的要素结构一致,坐标已转成 3857 */
  var seed = [
    { type: 'Point', coord: [116.391263, 39.907359], name: '天安门' },
    { type: 'Point', coord: [116.410600, 39.914700], name: '王府井' },
    { type: 'LineString', coords: [[116.352, 39.905], [116.374, 39.910], [116.392, 39.907]], name: '长安街西段' }
  ];

  var features = seed.map(function (item, i) {
    var geom;
    if (item.type === 'Point') {
      geom = new ol.geom.Point(ol.proj.fromLonLat(item.coord));
    } else {
      geom = new ol.geom.LineString(item.coords.map(function (c) {
        return ol.proj.fromLonLat(c);
      }));
    }
    return new ol.Feature({ geometry: geom, name: item.name, fid: i + 1 });
  });

  var source = new ol.source.Vector({ features: features });

  var style = new ol.style.Style({
    fill: new ol.style.Fill({ color: 'rgba(31,95,208,0.18)' }),
    stroke: new ol.style.Stroke({ color: '#1f5fd0', width: 2 }),
    image: new ol.style.Circle({
      radius: 6,
      fill: new ol.style.Fill({ color: '#1f5fd0' }),
      stroke: new ol.style.Stroke({ color: '#ffffff', width: 2 })
    }),
    text: new ol.style.Text({
      text: '',
      font: '500 12px sans-serif',
      offsetY: -14,
      fill: new ol.style.Fill({ color: '#16181d' }),
      stroke: new ol.style.Stroke({ color: '#ffffff', width: 3 })
    })
  });

  function styleFn(feature) {
    style.getText().setText(feature.get('name') || '');
    return style;
  }

  var vectorLayer = new ol.layer.Vector({ source: source, style: styleFn });

  var map = 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'}) }),
      vectorLayer
    ],
    view: new ol.View({
      center: ol.proj.fromLonLat([116.391, 39.907]),
      zoom: 13,
      minZoom: 2
    }),
    controls: ol.control.defaults.defaults({ attribution: false })
  });

  /* 编辑三件套:绘制、修改、捕捉 */
  var draw = null;
  var modify = new ol.interaction.Modify({ source: source });
  var snap = new ol.interaction.Snap({ source: source });
  var select = new ol.interaction.Select({
    condition: ol.events.condition.click,
    style: new ol.style.Style({
      stroke: new ol.style.Stroke({ color: '#e8590c', width: 3 }),
      image: new ol.style.Circle({
        radius: 7,
        fill: new ol.style.Fill({ color: '#e8590c' })
      })
    })
  });

  function stopDraw() {
    if (draw) {
      map.removeInteraction(draw);
      draw = null;
    }
  }

  function setMode(mode) {
    stopDraw();
    map.removeInteraction(modify);
    map.removeInteraction(snap);
    map.removeInteraction(select);

    if (mode === 'point' || mode === 'line' || mode === 'polygon') {
      var type = mode === 'point' ? 'Point' : (mode === 'line' ? 'LineString' : 'Polygon');
      draw = new ol.interaction.Draw({ source: source, type: type });
      draw.on('drawend', function (evt) {
        var count = source.getFeatures().length;
        evt.feature.set('name', '要素 ' + count);
      });
      map.addInteraction(draw);
      map.addInteraction(snap);
    } else if (mode === 'modify') {
      map.addInteraction(modify);
      map.addInteraction(snap);
    } else if (mode === 'delete') {
      map.addInteraction(select);
    }
    updateInfo();
  }

  function updateInfo() {
    infoEl.textContent = '当前要素数 ' + source.getFeatures().length;
  }

  select.on('select', function (evt) {
    evt.selected.forEach(function (f) { source.removeFeature(f); });
    updateInfo();
  });

  source.on('addfeature', updateInfo);
  source.on('removefeature', updateInfo);

  Array.prototype.forEach.call(
    document.querySelectorAll('[data-mode]'),
    function (btn) {
      btn.addEventListener('click', function () {
        Array.prototype.forEach.call(
          document.querySelectorAll('[data-mode]'),
          function (b) { b.classList.remove('on'); }
        );
        btn.classList.add('on');
        setMode(btn.getAttribute('data-mode'));
      });
    }
  );

  updateInfo();
})();
</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 · EXAMPLEVector Label Decluttering OpenLayers · EXAMPLEVector Labels OpenLayers · EXAMPLEVector Labels Justify Text