Box Select
Runnable MapLibre GL JS example: Box Select. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
示例:框选要素
核心逻辑:Shift 拖拽触发 boxzoomend,用返回的 bounds 查询要素并写 feature-state
数据:页面内生成的 120 个监测点,带编号与数值
依赖: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 button{background:#fff;border:1px solid #cfd6df;border-radius:4px;padding:3px 10px;
font:12px/1.4 inherit;color:#3a4250;cursor:pointer}
.bar button:hover{border-color:#2e86de;color:#2e86de}
#map{flex:1 1 auto;min-height:0}
</style>
</head>
<body>
<div class="bar">
<span>总数 <b>120</b></span>
<span>选中 <b id="n">0</b></span>
<button id="clear">清空选择</button>
<span>按住 Shift 在图上拖出一个框</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 cities = [
[116.39, 39.90], [121.47, 31.23], [113.26, 23.12], [104.06, 30.57],
[108.94, 34.34], [114.30, 30.59], [120.15, 30.28], [106.55, 29.56]
];
var features = [];
for (var i = 0; i < 120; i++) {
var c = cities[i % cities.length];
features.push({
type: 'Feature',
properties: { id: i, code: 'S' + (1000 + i), value: 10 + Math.round(Math.random() * 90) },
geometry: {
type: 'Point',
coordinates: [c[0] + (Math.random() - 0.5) * 4.5, c[1] + (Math.random() - 0.5) * 3.5]
}
});
}
var map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [110, 34],
zoom: 3.4,
attributionControl: { compact: true, customAttribution: 'MapLibre demo tiles' }
});
map.addControl(new maplibregl.NavigationControl(), 'top-right');
var nEl = document.getElementById('n');
var selected = [];
map.on('load', function () {
map.addSource('sensors', {
type: 'geojson',
data: { type: 'FeatureCollection', features: features },
promoteId: 'id'
});
map.addLayer({
id: 'sensors',
type: 'circle',
source: 'sensors',
paint: {
'circle-radius': ['case', ['boolean', ['feature-state', 'selected'], false], 7, 4],
'circle-color': ['case', ['boolean', ['feature-state', 'selected'], false], '#f03e3e', '#4dabf7'],
'circle-stroke-width': 1,
'circle-stroke-color': '#ffffff'
}
});
});
function clear() {
selected.forEach(function (id) {
map.setFeatureState({ source: 'sensors', id: id }, { selected: false });
});
selected = [];
nEl.textContent = 0;
}
/* boxzoomend 只在框选结束时触发一次,比监听拖拽过程省事 */
map.on('boxzoomend', function (e) {
if (!map.getLayer('sensors')) return;
clear();
var hit = map.queryRenderedFeatures(e.boxZoomBounds, { layers: ['sensors'] });
var seen = {};
hit.forEach(function (f) {
var id = f.properties.id;
if (seen[id]) return;
seen[id] = true;
selected.push(id);
map.setFeatureState({ source: 'sensors', id: id }, { selected: true });
});
nEl.textContent = selected.length;
});
document.getElementById('clear').addEventListener('click', clear);
map.on('mousemove', 'sensors', function (e) {
map.getCanvas().style.cursor = 'pointer';
var p = e.features[0].properties;
e.target.getCanvas().title = p.code + ' · ' + p.value;
});
map.on('mouseleave', 'sensors', function () {
map.getCanvas().style.cursor = '';
map.getCanvas().title = '';
});
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.