Atlaslog
Atlaslog / Examples / deck.gl / Business scenarios / Geofence Violation Analysis
deck.gl · Business scenario

Geofence Violation Analysis

Three rectangular and three circular fences laid over the urban area; 70,000 points coloured by side of the boundary, with switches for all points, inside only and violations only.

Open standalone → Chinese notes All business examples
/demos/deckgl-biz-city-fence.htmlLIVE
single HTML file · CDN dependencies onlyinterface labels are in Chinese

Business context

In shared-bike operations, hazardous-goods transport and monitored-person supervision, operators and regulators use fences to decide who is inside an area and who has crossed it, which drives dispatch, alerts and assessment. One side of the data is the fence definition such as no-parking zones, work areas and management boundaries; the other is timestamped positioning tracks. A city-level project typically has tens to hundreds of fences and millions of fixes per day; this example uses 70,000 points.

Fences are not stored as fixed vertices but parameterised by centre plus half-width and half-height, or centre plus a radius in metres, then expanded into rings. A circle must first project the lng/lat offset into metres at the current latitude, otherwise it becomes an ellipse at 40 degrees north. Points are normalised to WGS84 and the inside test runs on the CPU; the three views only swap the data reference of ScatterplotLayer while the outline layer keeps its instance, so nothing flickers when switching.

The common error is substituting a bounding box or centre distance for the real polygon: concave notches and the inner side of fences with holes are classified as inside, and violations are missed. Coverage figures also need a stated basis, by point or by area; counting by point is skewed by devices that report at a high rate. GPS drift near the boundary creates false violations, so production systems add a buffer or filter on dwell time.

How it works

Fences are not hardcoded with vertices but expressed as centre plus half-width and half-height, or centre plus a radius in metres, then expanded by ringFor: a rectangle takes four edges plus a closing point, and a circle is a 48-segment polyline with the longitude offset divided by 111320·cos(lat) to convert metres to degrees. Forty percent of the 70,000 points sit within 1.5–1.6 times the fence edge and the rest spread evenly inside the 116.26–116.56, 39.80–40.05 box, so both sides of each boundary hold enough samples and the inside view does not collapse into a few scattered points. The test compares lng/lat against half-width and half-height for rectangles, and projects the lng/lat offset into metres at the current latitude before comparing against the radius for circles, so circles are not stretched into ellipses at high latitude.

The three views replace only the data reference of ScatterplotLayer and leave the fence PolygonLayer untouched, so outlines do not flicker when switching. The violation ratio is computed once at initialisation and written to the toolbar, and is not recomputed on later switches. If fences become concave, a bounding box or centre distance misclassifies points in the notch as inside, and a ray cast is required: cast a ray to the right from the point and count edge crossings, odd meaning inside and even meaning outside, which is the same convention used by GeoJsonLayer and turf's booleanPointInPolygon.

ConfigurationWhat it does
Rectangular fenceCentre plus half-width and half-height, tested directly on the lng/lat range
Circular fenceCentre plus radius in metres, converted by latitude before planar distance
PolygonLayer outlinegetLineColor bright blue, getLineWidth 2 pixels, boundary reference only
Three-view switchReplaces ScatterplotLayer data while the fence layer keeps its instance

Note. Remove cos(lat) from the circular test and circles stretch about 30% east-west at 40 degrees north, so violation points are misclassified on both sides.

Source

demos/deckgl-biz-city-fence.html
<!--
  示例:电子围栏越界分析
  要点:矩形围栏按经纬范围判断、圆形围栏按米制距离判断,7 万点位分色并统计越界比例
  依赖:deck.gl 9.0 · 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>
<style>
  html,body{height:100%;margin:0;background:#0d1117}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#e6e8ec}
  .bar{position:relative;z-index:5;flex:0 0 auto;padding:8px 12px;background:#161b22;border-bottom:1px solid #252c36;
       display:flex;gap:12px;align-items:center;font-size:12px;color:#8b93a1;flex-wrap:wrap}
  .bar b{color:#58a6ff;font-weight:600}
  .bar button{font:inherit;font-size:12px;padding:3px 10px;border-radius:5px;cursor:pointer;
              border:1px solid #303845;background:#1d2531;color:#c8d2e0}
  .bar button:hover{background:#253040}
  .bar button.on{background:#2c4a7a;border-color:#4f8ad6;color:#dfe9ff}
  .bar .sep{width:1px;height:18px;background:#2a313c;margin:0 4px}
  #cv{flex:1 1 auto;min-height:0;width:100%;display:block}
</style>
</head>
<body>
<div class="bar">
  <span>越界比例 <b id="rate">—</b></span>
  <span>围栏内 <b id="inN">—</b> · 越界 <b id="outN">—</b></span>
  <span class="sep"></span>
  <button data-mode="all" class="on">全部</button>
  <button data-mode="in">围栏内</button>
  <button data-mode="out">越界</button>
</div>
<canvas id="cv"></canvas>
<script src="https://cdn.jsdelivr.net/npm/deck.gl@9.0.35/dist.min.js"></script>
<script>
(function () {
  'use strict';

  if (typeof deck === 'undefined') {
    document.body.innerHTML =
      '<div style="padding:24px;color:#ff8c74">deck.gl 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  function rng(seed) {
    var a = seed >>> 0;
    return function () {
      a = (a + 0x6D2B79F5) >>> 0;
      var t = Math.imul(a ^ (a >>> 15), 1 | a);
      t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
      return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
    };
  }

  var rand = rng(51066);

  var DEG_LAT = 110540;
  var DEG_LNG = 111320;

  // 3 个矩形 + 3 个圆形,矩形用半宽半高、圆形用米制半径参数化
  var fences = [
    { type: 'rect', cx: 116.332, cy: 39.958, hw: 0.040, hh: 0.026 },
    { type: 'rect', cx: 116.492, cy: 39.918, hw: 0.036, hh: 0.024 },
    { type: 'rect', cx: 116.398, cy: 39.848, hw: 0.044, hh: 0.022 },
    { type: 'circle', cx: 116.362, cy: 39.902, r: 2400 },
    { type: 'circle', cx: 116.470, cy: 39.982, r: 2100 },
    { type: 'circle', cx: 116.452, cy: 39.888, r: 3000 }
  ];

  function ringFor(f) {
    var ring = [];
    var i;
    if (f.type === 'rect') {
      ring.push([f.cx - f.hw, f.cy - f.hh]);
      ring.push([f.cx + f.hw, f.cy - f.hh]);
      ring.push([f.cx + f.hw, f.cy + f.hh]);
      ring.push([f.cx - f.hw, f.cy + f.hh]);
      ring.push([f.cx - f.hw, f.cy - f.hh]);
    } else {
      var k = DEG_LNG * Math.cos(f.cy * Math.PI / 180);
      for (i = 0; i <= 48; i++) {
        var a = i / 48 * Math.PI * 2;
        ring.push([f.cx + Math.cos(a) * f.r / k, f.cy + Math.sin(a) * f.r / DEG_LAT]);
      }
    }
    return ring;
  }

  for (var f = 0; f < fences.length; f++) {
    fences[f].ring = ringFor(fences[f]);
  }

  // 坐标范围判断矩形,投影到米后算距离判断圆形
  function inFence(p, fence) {
    if (fence.type === 'rect') {
      return p.lng >= fence.cx - fence.hw && p.lng <= fence.cx + fence.hw &&
             p.lat >= fence.cy - fence.hh && p.lat <= fence.cy + fence.hh;
    }
    var dx = (p.lng - fence.cx) * DEG_LNG * Math.cos(p.lat * Math.PI / 180);
    var dy = (p.lat - fence.cy) * DEG_LAT;
    return Math.sqrt(dx * dx + dy * dy) <= fence.r;
  }

  var points = [];
  var insidePts = [];
  var outsidePts = [];

  for (var i = 0; i < 70000; i++) {
    var p;
    if (i % 5 < 2) {
      // 四成点位贴着围栏生成,保证边界内外都有足够样本
      var fence = fences[i % fences.length];
      if (fence.type === 'rect') {
        p = {
          lng: fence.cx + (rand() * 2 - 1) * fence.hw * 1.6,
          lat: fence.cy + (rand() * 2 - 1) * fence.hh * 1.6
        };
      } else {
        var dist = Math.sqrt(rand()) * fence.r * 1.5;
        var ang = rand() * Math.PI * 2;
        p = {
          lng: fence.cx + Math.cos(ang) * dist / (DEG_LNG * Math.cos(fence.cy * Math.PI / 180)),
          lat: fence.cy + Math.sin(ang) * dist / DEG_LAT
        };
      }
    } else {
      p = { lng: 116.26 + rand() * 0.30, lat: 39.80 + rand() * 0.25 };
    }

    p.inside = false;
    for (var j = 0; j < fences.length; j++) {
      if (inFence(p, fences[j])) {
        p.inside = true;
        break;
      }
    }
    points.push(p);
    if (p.inside) insidePts.push(p);
    else outsidePts.push(p);
  }

  document.getElementById('rate').textContent =
    (outsidePts.length / points.length * 100).toFixed(1) + '%';
  document.getElementById('inN').textContent = insidePts.length.toLocaleString();
  document.getElementById('outN').textContent = outsidePts.length.toLocaleString();

  var fenceLayer = new deck.PolygonLayer({
    id: 'fence-rings',
    data: fences,
    getPolygon: function (d) { return d.ring; },
    filled: true,
    getFillColor: [64, 154, 255, 22],
    stroked: true,
    getLineColor: [92, 170, 255, 235],
    getLineWidth: 2,
    lineWidthUnits: 'pixels'
  });

  function makePoints(mode) {
    var data = points;
    if (mode === 'in') data = insidePts;
    if (mode === 'out') data = outsidePts;
    return new deck.ScatterplotLayer({
      id: 'fence-points',
      data: data,
      getPosition: function (d) { return [d.lng, d.lat]; },
      getRadius: 2.2,
      radiusUnits: 'pixels',
      getFillColor: function (d) {
        return d.inside ? [86, 214, 168, 155] : [240, 104, 72, 155];
      },
      stroked: false,
      opacity: 0.9
    });
  }

  var pointLayer = makePoints('all');

  var deckgl = new deck.Deck({
    canvas: 'cv',
    width: '100%',
    height: '100%',
    initialViewState: {
      longitude: 116.38,
      latitude: 39.91,
      zoom: 10.4,
      pitch: 0,
      bearing: 0
    },
    controller: true,
    layers: [pointLayer, fenceLayer]
  });

  var buttons = document.querySelectorAll('[data-mode]');
  for (var b = 0; b < buttons.length; b++) {
    buttons[b].addEventListener('click', function (e) {
      var mode = e.currentTarget.getAttribute('data-mode');
      for (var k = 0; k < buttons.length; k++) {
        buttons[k].classList.toggle('on', buttons[k] === e.currentTarget);
      }
      pointLayer = makePoints(mode);
      deckgl.setProps({ layers: [pointLayer, fenceLayer] });
    });
  }

  window.__deck = deckgl;
})();
</script>
</body>
</html>
Language: this page is in English; the demo keeps Chinese interface labels and code comments. The Chinese page carries the full notes and the same runnable file.

More business examples

deck.gl · APIPolygonLayer deck.gl · APIScatterplotLayer deck.gl · APIGeoJsonLayer