Atlaslog
Atlaslog / Examples / OpenLayers / Hitdetect Vector
OpenLayers · Runnable Example

Hitdetect Vector

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

Source

demos/openlayers-hitdetect-vector.html
<!--
  示例:矢量要素命中检测
  要点:forEachFeatureAtPixel 判定光标下的要素,配合图层过滤与命中容差
  依赖: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;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 b{color:#16181d;font-weight:600}
  .bar input[type=range]{width:100px}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <span>命中:<b id="hit">—</b></span>
  <span>命中数:<b id="hits">0</b></span>
  <label for="tol">容差 <b id="tolv">6</b>px</label>
  <input type="range" id="tol" min="1" max="20" step="1" value="6">
</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 fromLonLat = ol.proj.fromLonLat;

  var polygons = [
    { name: '西城片区', ring: [[116.30, 39.945], [116.372, 39.945], [116.372, 39.885], [116.30, 39.885]] },
    { name: '东城片区', ring: [[116.392, 39.955], [116.468, 39.955], [116.468, 39.893], [116.392, 39.893]] },
    { name: '丰台片区', ring: [[116.418, 39.878], [116.500, 39.878], [116.500, 39.812], [116.418, 39.812]] }
  ];

  var baseStyle = new ol.style.Style({
    fill: new ol.style.Fill({ color: 'rgba(31,95,208,0.18)' }),
    stroke: new ol.style.Stroke({ color: '#1f5fd0', width: 1.5 })
  });

  var hoverStyle = new ol.style.Style({
    fill: new ol.style.Fill({ color: 'rgba(250,193,86,0.45)' }),
    stroke: new ol.style.Stroke({ color: '#a9700f', width: 2.5 }),
    text: new ol.style.Text({
      font: '600 13px sans-serif',
      fill: new ol.style.Fill({ color: '#7a4d00' }),
      stroke: new ol.style.Stroke({ color: '#ffffff', width: 3 })
    })
  });

  var features = polygons.map(function (p) {
    var f = new ol.Feature({
      geometry: new ol.geom.Polygon([p.ring.map(function (c) { return fromLonLat(c); })]),
      name: p.name
    });
    f.setStyle(baseStyle);
    return f;
  });

  var points = [[116.34, 39.92], [116.43, 39.93], [116.46, 39.845]].map(function (c, i) {
    return new ol.Feature({
      geometry: new ol.geom.Point(fromLonLat(c)),
      name: '站点 ' + (i + 1),
      style: new ol.style.Style({
        image: new ol.style.Circle({
          radius: 5,
          fill: new ol.style.Fill({ color: '#b42318' }),
          stroke: new ol.style.Stroke({ color: '#ffffff', width: 2 })
        })
      })
    });
  });

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

  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'}) }), layer],
    view: new ol.View({ center: fromLonLat([116.40, 39.90]), zoom: 12 }),
    controls: ol.control.defaults.defaults({ rotate: false })
  });

  var tolerance = 6;
  var hovered = null;

  map.on('pointermove', function (evt) {
    if (evt.dragging) return;

    var named = [];
    map.forEachFeatureAtPixel(evt.pixel, function (feature) {
      named.push(feature.get('name'));
    }, {
      layerFilter: function (l) { return l === layer; },
      hitTolerance: tolerance
    });

    var top = null;
    map.forEachFeatureAtPixel(evt.pixel, function (feature) { top = feature; }, {
      layerFilter: function (l) { return l === layer; },
      hitTolerance: tolerance
    });

    if (hovered !== top) {
      if (hovered && hovered.getGeometry().getType() === 'Polygon') hovered.setStyle(baseStyle);
      if (top && top.getGeometry().getType() === 'Polygon') {
        var s = hoverStyle.clone();
        s.getText().setText(top.get('name'));
        top.setStyle(s);
      }
      hovered = top;
      map.getTargetElement().style.cursor = top ? 'pointer' : '';
    }

    document.getElementById('hit').textContent = named.length ? named[0] : '—';
    document.getElementById('hits').textContent = named.length;
  });

  document.getElementById('tol').addEventListener('input', function () {
    tolerance = Number(this.value);
    document.getElementById('tolv').textContent = tolerance;
  });
})();
</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 · EXAMPLEHit Tolerance OpenLayers · EXAMPLEHover Tooltip OpenLayers · EXAMPLEIcon