MapBox随机化建筑物颜色 功能状态准随机

问题描述

是否可以遍历地图上的所有建筑物,为它们分配不同的颜色或驱动主题分组的不同属性值?

我有遍历建筑物的代码

features = map.queryRenderedFeatures({ layers: ["building"],filter: ['==','extrude','true']});
features.forEach(function(feature){
  // how to change feature colour or property in here?
}

解决方法

有两种方法可以实现您想要的东西。

功能状态

如果您的建筑物图层具有要素ID,则可以使用setFeatureState在每个建筑物上设置状态。

features = map.querySourceFeatures('building',{ sourceLayer: 'buildings' }));
features.forEach(function(feature){
  if (!map.getFeatureState({ id: feature.id,source: 'building',sourceLayer: 'buildings' }).color) {
    map.setFeatureState({ id: feature.id,sourceLayer: 'buildings' },{ color: makeRandomColor() }
  }
});

然后可以在表达式中使用['feature-state','color']

准随机

如果没有功能部件ID,您也许可以以某种随机的方式使用其他属性。例如,如果还有其他类型的ID,则可以使用mod函数将其映射到一种颜色,看起来可能是随机的。