Atlaslog
Atlaslog / Examples / OpenLayers / Snap
OpenLayers · Runnable Example

Snap

Runnable OpenLayers example: Snap. 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-snap.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-snap.html
<!--
  示例:绘制吸附
  要点:Draw 画多边形时,Snap 把顶点拉到已有道路折线上
  依赖:OpenLayers 10.3.1 · jsDelivr CDN(底图 OSM,无 Key)
-->
<!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;color:#16181d}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  .bar b{color:#16181d;font-weight:600}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <label><input type="checkbox" id="snap" checked> 吸附到道路</label>
  <span>吸附容差 <b id="tol">10</b> 像素</span>
  <input type="range" id="tolR" min="4" max="24" value="10" style="width:110px">
  <span>绘制要素 <b id="n">0</b></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 (!window.ol) {
    document.getElementById('map').textContent = 'OpenLayers 加载失败,请检查 cdn.jsdelivr.net 是否可访问';
    return;
  }

  /* 两条示意道路,作为吸附目标 */
  var roads = [
    [[116.330, 39.900], [116.380, 39.906], [116.430, 39.900], [116.470, 39.912]],
    [[116.400, 39.860], [116.402, 39.900], [116.410, 39.940], [116.408, 39.970]]
  ].map(function (line) {
    return new ol.Feature(new ol.geom.LineString(
      line.map(function (c) { return ol.proj.fromLonLat(c); })
    ));
  });

  var roadLayer = new ol.layer.Vector({
    source: new ol.source.Vector({ features: roads }),
    style: new ol.style.Style({
      stroke: new ol.style.Stroke({ color: '#8a92a1', width: 5, lineCap: 'round' })
    })
  });

  var drawSource = new ol.source.Vector();
  var drawLayer = new ol.layer.Vector({
    source: drawSource,
    style: new ol.style.Style({
      fill: new ol.style.Fill({ color: 'rgba(31,95,208,.18)' }),
      stroke: new ol.style.Stroke({ color: '#1f5fd0', width: 2 })
    })
  });

  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'}) }),
      roadLayer,
      drawLayer
    ],
    view: new ol.View({ center: ol.proj.fromLonLat([116.400, 39.920]), zoom: 13 }),
    controls: ol.control.defaults.defaults({ attribution: false, rotate: false })
  });

  var draw = new ol.interaction.Draw({
    source: drawSource,
    type: 'Polygon'
  });
  map.addInteraction(draw);

  /* Snap 的容差在构造时固定,改容差就替换交互实例 */
  function rebuildSnap(tolerance) {
    if (snap) map.removeInteraction(snap);
    snap = new ol.interaction.Snap({
      source: roadLayer.getSource(),
      pixelTolerance: tolerance
    });
    snap.setActive(document.getElementById('snap').checked);
    map.addInteraction(snap);
  }

  var snap = null;
  rebuildSnap(10);

  drawSource.on('addfeature', function () {
    document.getElementById('n').textContent = drawSource.getFeatures().length;
  });

  document.getElementById('snap').addEventListener('change', function () {
    snap.setActive(this.checked);
  });

  document.getElementById('tolR').addEventListener('input', function () {
    document.getElementById('tol').textContent = this.value;
    rebuildSnap(Number(this.value));
  });
})();
</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 · EXAMPLESnap Draw OpenLayers · EXAMPLESphere Mollweide OpenLayers · EXAMPLEStac Item