首页 / MapLibre / API 文档
queryRenderedFeatures
先看结论
查询当前画面上真正渲染出来的要素,返回 GeoJSON Feature 数组,是点选、框选与悬停的基础。
map.queryRenderedFeatures(geometry?, options?) → GeoJSONFeature[]
参数
| 参数 | 类型 | 说明 |
|---|---|---|
geometry | PointLike | [PointLike, PointLike] | 查询点或矩形,坐标是相对地图容器的像素;省略时查询整个视口 |
options.layers | string[] | 只查这些图层,省略时查所有可见图层 |
options.filter | FilterSpecification | 附加属性过滤,写法与图层 filter 相同 |
options.validate | boolean | 是否校验过滤表达式,默认 true;批量查询时可关掉提速 |
PointLike 可以是 Point、[x, y] 或 { x, y }。
矩形写成两个点组成的数组:[[x1, y1], [x2, y2]]。
点选
map.on('click', function (e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['district-fill', 'poi-circle']
});
if (!features.length) {
return;
}
var f = features[0];
new maplibregl.Popup()
.setLngLat(e.lngLat)
.setHTML('<b>' + (f.properties.name || f.properties.NAME) + '</b>')
.addTo(map);
});
e.point 已经是容器像素坐标,可直接使用。
自己构造坐标时要相对容器左上角,页面坐标会因滚动与布局偏移。
框选
function queryBox(topLeft, bottomRight) {
return map.queryRenderedFeatures(
[topLeft, bottomRight],
{
layers: ['poi-circle'],
filter: ['==', ['get', 'status'], 'active']
}
);
}
/* 以点击位置为中心取 10×10 像素的小框,容错更友好 */
var pad = 5;
var box = [
[e.point.x - pad, e.point.y - pad],
[e.point.x + pad, e.point.y + pad]
];
var hits = map.queryRenderedFeatures(box, { layers: ['poi-circle'] });
返回值的形态
| 字段 | 说明 |
|---|---|
type | 固定为 'Feature' |
geometry | 要素几何,坐标已是经纬度 |
properties | 要素属性,字符串与数字保持原类型 |
layer | 命中图层的信息,含 id、type、source |
source | 源 id |
id | 要素 id,源未提供时为 undefined |
properties 里的属性名取决于数据源。矢量瓦片常用大写字段,
GeoJSON 保留原始大小写,取属性前先确认数据。
只查渲染结果的原因
查询只看当前视口、当前缩放、当前过滤条件下已经画出来的要素:
被 minzoom 隐藏的、被过滤条件排除的、视野外的都不会出现。
需要全量数据时不要用它,应该查询自己的数据源或接口。
瓦片边界上的要素可能出现在相邻瓦片里,同一要素因此重复返回。
做计数统计时先按 id 或业务主键去重。
结果顺序不是绘制顺序。
同一位置若有多个图层重叠,返回数组的顺序不保证按图层从下到上排列。
需要「点最上面的那个」时,用 layer.id 对照自己的图层优先级挑选。
经纬志(2026)。《queryRenderedFeatures》。https://www.jingweizhi.com/maplibre/api/query-rendered-features.html(访问日期 2026-11-03)。