Atlaslog
Atlaslog / Examples / MapLibre GL JS / Filter By Text
MapLibre GL JS · Runnable Example

Filter By Text

Runnable MapLibre GL JS example: Filter By Text. 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-filter-by-text.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/maplibre-filter-by-text.html
<!--
  示例:按输入过滤符号
  核心逻辑:输入框拼出名称数组,setFilter 用 in 表达式按属性筛要素
  数据:页面内写死的 20 个城市,带拼音首字母便于检索
  依赖: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 input[type=search]{width:180px;padding:4px 8px;border:1px solid #cfd6df;border-radius:4px;
      font:12px/1.4 inherit;color:#16181d}
  .bar button{background:#fff;border:1px solid #cfd6df;border-radius:4px;padding:3px 10px;
      font:12px/1.4 inherit;color:#3a4250;cursor:pointer}
  #map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
  <span>显示 <b id="n">20</b> / 20</span>
  <input id="q" type="search" placeholder="输入城市名或首字母,如 北 / bj">
  <button id="reset">重置</button>
</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 raw = [
    ['北京', 'bj', 116.39, 39.90], ['上海', 'sh', 121.47, 31.23],
    ['广州', 'gz', 113.26, 23.12], ['深圳', 'sz', 114.06, 22.54],
    ['成都', 'cd', 104.06, 30.57], ['重庆', 'cq', 106.55, 29.56],
    ['天津', 'tj', 117.20, 39.13], ['武汉', 'wh', 114.30, 30.59],
    ['西安', 'xa', 108.94, 34.34], ['杭州', 'hz', 120.15, 30.28],
    ['南京', 'nj', 118.80, 32.06], ['沈阳', 'sy', 123.43, 41.80],
    ['青岛', 'qd', 120.38, 36.07], ['大连', 'dl', 121.61, 38.91],
    ['昆明', 'km', 102.71, 25.04], ['厦门', 'xm', 118.09, 24.48],
    ['哈尔滨', 'heb', 126.64, 45.75], ['乌鲁木齐', 'wlmq', 87.61, 43.82],
    ['拉萨', 'ls', 91.11, 29.65], ['海口', 'hk', 110.20, 20.04]
  ];

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

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

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

  var qEl = document.getElementById('q');
  var nEl = document.getElementById('n');

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

    map.addLayer({
      id: 'city-dot',
      type: 'circle',
      source: 'cities',
      paint: {
        'circle-radius': 5,
        'circle-color': '#2e86de',
        'circle-stroke-width': 1.5,
        'circle-stroke-color': '#ffffff'
      }
    });

    map.addLayer({
      id: 'city-label',
      type: 'symbol',
      source: 'cities',
      layout: {
        'text-field': ['get', 'name'],
        'text-font': ['Noto Sans Regular'],
        'text-size': 12,
        'text-offset': [0, 1.1],
        'text-anchor': 'top'
      },
      paint: {
        'text-color': '#1f2d3d',
        'text-halo-color': '#ffffff',
        'text-halo-width': 1.4
      }
    });
  });

  function apply(q) {
    if (!map.getLayer('city-dot')) return;

    var key = q.trim().toLowerCase();
    if (!key) {
      map.setFilter('city-dot', null);
      map.setFilter('city-label', null);
      nEl.textContent = features.length;
      return;
    }

    /* 命中集合以数组字面量传给 in 表达式 */
    var names = features.filter(function (f) {
      return f.properties.name.indexOf(key) >= 0 || f.properties.py.indexOf(key) >= 0;
    }).map(function (f) { return f.properties.name; });

    var expr = ['in', ['get', 'name'], ['literal', names]];
    map.setFilter('city-dot', expr);
    map.setFilter('city-label', expr);
    nEl.textContent = names.length;
  }

  qEl.addEventListener('input', function () {
    apply(this.value);
  });

  document.getElementById('reset').addEventListener('click', function () {
    qEl.value = '';
    apply('');
  });

  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 · EXAMPLEFit Bounds MapLibre GL JS · EXAMPLEFly to MapLibre GL JS · EXAMPLEGeoJSON Line