Atlaslog
Atlaslog / Examples / MapLibre GL JS / Popup on Click
MapLibre GL JS · Runnable Example

Popup on Click

Runnable MapLibre GL JS example: Popup on Click. 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-popup-on-click.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/maplibre-popup-on-click.html
<!--
  示例:点击弹窗
  核心逻辑:click 落在图层上时,用事件自带的 lngLat 定位 Popup,再填入要素属性
  数据:页面内构造的 9 条告警记录,每条带等级与时间
  依赖: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}
  #map{flex:1 1 auto;min-height:0}
  .card{font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#16181d;min-width:160px}
  .card h4{margin:0 0 4px;font-size:14px}
  .card .lv{display:inline-block;padding:1px 6px;border-radius:3px;font-size:11px;color:#fff}
</style>
</head>
<body>
<div class="bar">
  <span>告警 <b id="n">—</b></span>
  <span>已点击 <b id="cur">—</b></span>
  <span>点击圆点打开弹窗,再点地图空白处关闭</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 LEVEL = { 1: '#f03e3e', 2: '#f59f00', 3: '#2e86de' };

  var raw = [
    ['管道压力异常', 116.42, 39.92, 1, '08:12'],
    ['设备离线', 121.51, 31.28, 2, '09:35'],
    ['积水告警', 113.30, 23.15, 1, '10:02'],
    ['流量偏低', 104.09, 30.61, 3, '11:20'],
    ['温度超限', 108.92, 34.31, 2, '12:44'],
    ['电压波动', 114.33, 30.56, 3, '13:10'],
    ['阀门未关', 120.18, 30.31, 2, '14:05'],
    ['通信中断', 106.51, 29.59, 1, '15:31'],
    ['巡检超时', 118.83, 32.09, 3, '16:18']
  ];

  var features = raw.map(function (r) {
    return {
      type: 'Feature',
      properties: { name: r[0], level: r[3], time: r[4], color: LEVEL[r[3]] },
      geometry: { type: 'Point', coordinates: [r[1], r[2]] }
    };
  });

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

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

  var nEl = document.getElementById('n');
  var curEl = document.getElementById('cur');
  nEl.textContent = features.length;

  /* 一个弹窗实例复用,每次点击只改内容与位置 */
  var popup = new maplibregl.Popup({ offset: 12, maxWidth: '260px' });

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

    map.addLayer({
      id: 'alerts',
      type: 'circle',
      source: 'alerts',
      paint: {
        'circle-radius': 8,
        'circle-color': ['get', 'color'],
        'circle-stroke-width': 2,
        'circle-stroke-color': '#ffffff'
      }
    });
  });

  map.on('click', 'alerts', function (e) {
    if (!e.features.length) return;
    var f = e.features[0];
    var p = f.properties;

    curEl.textContent = p.name;

    popup
      .setLngLat(e.lngLat)
      .setHTML(
        '<div class="card"><h4>' + p.name + '</h4>' +
        '<span class="lv" style="background:' + p.color + '">等级 ' + p.level + '</span>' +
        ' <span style="color:#888">' + p.time + '</span>' +
        '<div style="margin-top:4px;color:#666">' + e.lngLat.lng.toFixed(3) + ', ' +
        e.lngLat.lat.toFixed(3) + '</div></div>'
      )
      .addTo(map);
  });

  /* 点在空白处时收起弹窗,点击圆点的事件不会触发这里 */
  map.on('click', function (e) {
    if (!map.getLayer('alerts')) return;
    var hit = map.queryRenderedFeatures(e.point, { layers: ['alerts'] });
    if (!hit.length) {
      popup.remove();
      curEl.textContent = '—';
    }
  });

  map.on('mouseenter', 'alerts', function () {
    map.getCanvas().style.cursor = 'pointer';
  });
  map.on('mouseleave', 'alerts', function () {
    map.getCanvas().style.cursor = '';
  });

  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 · EXAMPLEPopup on Hover MapLibre GL JS · EXAMPLERaster Tiles MapLibre GL JS · EXAMPLERealtime Stream