首页 > 解决方案 > 如何在 Mapbox GL map.setFilter 中使用“in”表达式

问题描述

我正在尝试根据一组条件过滤 geoJson 图层(称为“目的地”)。我的“目的地”层有一个称为uniqueID字符串类型的属性,大多数时候它只有一个数字 ID,但有时有多个。我想map.setFilter根据一组 ID 过滤这一层(使用 )。过滤器应该这样做:如果uniqueID在 ID 数组中找到“目标”层中的任何值,则过滤掉该特征。

这是我的“目的地”层的片段:

{ "type": "Feature", "properties": { "destinationLon": -74.20716879, "destinationLat": 40.69097357, "uniqueID": "2029" }, "geometry": { "type": "Point", "coordinates": [ -74.20716879, 40.69097357 ] } },
{ "type": "Feature", "properties": { "destinationLon": -74.20670807, "destinationLat": 40.69137214, "uniqueID": "984,985" }, "geometry": { "type": "Point", "coordinates": [ -74.20670807, 40.69137214 ] } },
{ "type": "Feature", "properties": { "destinationLon": -74.20651489, "destinationLat": 40.71887889, "uniqueID": "1393" }, "geometry": { "type": "Point", "coordinates": [ -74.20651489, 40.71887889 ] } }

这是我可能使用的 ID 数组示例:[2000, 984, 1393]

我尝试使用这样的in表达式(此处的文档)使用过滤器:

let thisFilter = ["any"].concat(uniqueIDs.map(id => ["in", id, ["get", "uniqueID"]]));
map.setFilter("destinations", thisFilter);

但我不断收到此错误消息:

Error: "layers.destinations.filter[0][2]: string, number, or boolean expected, array found"

但是,文档说明了以下内容:

["in",
    keyword: InputType (boolean, string, or number),
    input: InputType (array or string)
]: boolean

表达式中的第三个参数应该是一个数组。那为什么我会收到这个错误?

有任何想法吗?谢谢!

标签: mapboxmapbox-gl-js

解决方案


我认为您的错误与in. 你可以通过简化你的表达,并any从各个in部分中分离出来来发现这一点。

您的错误是any采用可变数量的参数:

['any', ['in', ...], ['in', ...]]

而您正在传递一个数组:

['any', [['in', ...], ['in', ...]]]

我会像这样重写你的表达式:

let thisFilter = ["any", ...uniqueIDs.map(id => ["in", id, ["get", "uniqueID"]])];

推荐阅读