美文网首页
mapbox的filter

mapbox的filter

作者: 姜治宇 | 来源:发表于2023-08-24 14:38 被阅读0次

filter是layer里面的一个很有用的属性,可以通过一些条件表达式,用来只显示与过滤条件匹配的要素。
filter的使用前提,是需要在数据声明阶段,在每一个feature元素都赋予相应的properties属性信息,否则无法进行筛选。

const places = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'name': '昌平区',
'count': 18
},
'geometry': {
'type': 'Point',
'coordinates': [107.038659, 38.931567]
}
},
{
'type': 'Feature',
'properties': {
'name': '朝阳区',
'count': 17
},
'geometry': {
'type': 'Point',
'coordinates': [107.003168, 38.894651]
}
},
...
]

过滤条件主要分为如下几种方式:

1、==和!=

==和!=可实现根据某个字段图层的过滤展示。

// 只在地图上展示昌平区
map.setFilter('bj-dict', ['==', 'name','昌平区']);
//地图上展示除昌平外的所有区域
map.setFilter('bj-dict', ['!=', 'name','昌平区']);

2、>、>=、<、<=

>、>=、<、<=是通过比较大小的方式,实现图层的过滤,所以此处需要的字段得是数字类型。

map.setFilter('bj-dict', ['>=', 'count', 10]);

3、in和match

in和match可实现对图层根据某个字段进行多值过滤。
以下是筛选name不是昌平区和海淀区的数据。

map.setFilter('bj-dict', [
  '!in', 
  'name',
  '昌平区',
  '海淀区'
]);
map.setFilter('bj-dict', [
  "match",
  [
    "get",
    "name"
  ],
  [
    "昌平区",
    "海淀区",
  ],
  false,
  true
]);

其中match不仅可以匹配信息,还可以根据匹配的信息设置不同的值,所以是最为常用的。比如点击某个元素高亮显示。

map.addLayer({
'id': 'route',
'type': 'line',
'source': 'route',
'paint': {
'line-color': '#888',
'line-width': 8
}
});
changLineColor(1);
function changLineColor(currentIndex = 0) { // currentIndex为当前点击的要素序号
  map.setPaintProperty(
     'route',
     'line-color',
     ['match', ['get', 'index'], currentIndex, 'red', 'black']
  );//点击某个要素变红色,其他的为黑色。
}

满足type为1的为红色,type为2的为蓝色,其余为黑色:

function changLineColor() { 
  map.setPaintProperty(
     'route',
     'line-color',
     ['match', ['get', 'type'], 1, 'red', 2, 'blue',  'black']
  );

4、多条件

map.setFilter('bj-dict',[
  'all',
  ['>=', 'count', 10],
  ['==', 'name', '海淀区']
]);

参考资料:
https://blog.csdn.net/GISShiXiSheng/article/details/105157145

相关文章

网友评论

      本文标题:mapbox的filter

      本文链接:https://www.haomeiwen.com/subject/tugmmdtx.html