Atlaslog
Atlaslog / Examples / MapLibre GL JS / Label Collision
MapLibre GL JS · Runnable Example

Label Collision

Runnable MapLibre GL JS example: Label Collision. 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 MapLibre GL JS examples
/demos/maplibre-label-collision.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/maplibre-label-collision.html
<!--
  示例:标注避让
  核心逻辑:symbol 图层默认做碰撞检测,queryRenderedFeatures 统计实际绘出的标注数量
  依赖:MapLibre GL JS 4 · jsDelivr CDN · demotiles 样式与字形
-->
<!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/maplibre-gl@4/dist/maplibre-gl.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;display:flex;gap:14px;align-items:center;padding:8px 12px;
       background:#f6f7f9;border-bottom:1px solid #e3e6ea;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar b{color:#16181d;font-weight:600}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <label><input id="overlap" type="checkbox"> 允许重叠</label>
  <span>总标注 <b>150</b></span>
  <span>实际绘出 <b id="shown">—</b></span>
  <span>缩放 <b id="z">—</b></span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@4/dist/maplibre-gl.js"></script>
<script>
(function () {
  'use strict';

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

  var features = [];
  for (var i = 0; i < 150; i++) {
    features.push({
      type: 'Feature',
      properties: { code: 'P' + (100 + i) },
      geometry: {
        type: 'Point',
        coordinates: [
          103.0 + Math.random() * 8.5,
          29.0 + Math.random() * 5.2
        ]
      }
    });
  }

  var map = new maplibregl.Map({
    container: 'map',
    style: 'https://demotiles.maplibre.org/style.json',
    center: [107.2, 31.6],
    zoom: 6,
    attributionControl: { compact: true, customAttribution: 'MapLibre demo tiles' }
  });

  map.addControl(new maplibregl.NavigationControl(), 'top-right');

  map.on('load', function () {
    map.addSource('labels', {
      type: 'geojson',
      data: { type: 'FeatureCollection', features: features }
    });

    map.addLayer({
      id: 'labels',
      type: 'symbol',
      source: 'labels',
      layout: {
        'text-field': ['get', 'code'],
        'text-font': ['Noto Sans Regular'],
        'text-size': 12,
        'text-allow-overlap': false,
        'text-ignore-placement': false
      },
      paint: {
        'text-color': '#1b3350',
        'text-halo-color': '#ffffff',
        'text-halo-width': 1.4
      }
    });

    map.once('idle', count);
  });

  function count() {
    var shown = map.queryRenderedFeatures({ layers: ['labels'] }).length;
    document.getElementById('shown').textContent = shown;
  }

  document.getElementById('overlap').addEventListener('change', function () {
    var on = this.checked;
    map.setLayoutProperty('labels', 'text-allow-overlap', on);
    map.setLayoutProperty('labels', 'text-ignore-placement', on);
    map.once('idle', count);
  });

  map.on('moveend', function () {
    document.getElementById('z').textContent = map.getZoom().toFixed(2);
    map.once('idle', count);
  });

  map.on('error', function (e) {
    if (e.error) console.warn('地图错误:' + e.error.message);
  });
})();
</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 MapLibre GL JS examples

MapLibre GL JS · EXAMPLELayer Color Buttons MapLibre GL JS · EXAMPLELayer Switch MapLibre GL JS · EXAMPLELayer Visibility