Mapbox GL JS:在大型GeoJSON中为单个功能着色 [英] Mapbox GL JS: Coloring individual features in large GeoJSON
问题描述
我有一个状态图,每个区都作为Mapbox中的一个单独功能.我想根据党派票数之间的差异来更改每个区的颜色. 这是我要实现的目标的一个示例与
I have a map of states with each precinct as an individual feature in Mapbox. I want to change the color of each of these precincts based on the difference between party votes. Here's an example of what I'm trying to achieve versus what I have right now.
我尝试使用map.setPaintProperty,但是设置一项功能会迫使您更改与ID不匹配的所有其他功能.
I tried using map.setPaintProperty, however setting one feature forces you to change every other feature that doesn't match the ID.
map.setPaintProperty("wisconsin", "fill-color",
["match",["get", "id"],
features[i].properties["OBJECTID"],
color, "#ffffff"
]
);
我该如何解决?还是有另一种方法?
How could I go about this or is there another method of doing so?
推荐答案
因此,您想进行数据驱动的样式设置.基本上有三种方法.
So, you want to do data-driven styling. There are basically three methods.
如果要可视化的属性位于数据中(即,每个要素上都有一个.population
属性),请使用类似以下表达式:
If the attribute you want to visualise is in the data (ie, you have a .population
property on each feature), you use an expression like:
'fill-color': ['interpolate-hcl', ['linear'], ['get', 'population'], 0, 'red', 1e6, 'blue']
请参见 https://docs.mapbox.com/help/glossary /data-driven-styleling/
如果您的属性未包含在数据源中,则可以以编程方式生成一个巨大的表达式,如下所示:
If your attributes are not contained within your data source, you can programmatically generate a huge expression that will look like:
'fill-color': ['match', ['get', 'id'],
1020, 'red',
1033, 'green',
1038, 'red',
1049, 'white',
// ...
使用功能状态在运行时添加属性
最后,通过调用setFeatureState
在运行时实际添加所需的属性,尽管具有一些额外的复杂性,但您可以获得比前一种情况更好的渲染性能.
Use feature-state to add the attribute at run-time
Finally, you can get better rendering performance than the previous case, albeit with some extra complexity, by calling setFeatureState
to actually add the attribute you want at runtime.
您的样式如下:
'fill-color': ['interpolate-hcl', ['linear'], ['feature-state', 'population'], 0, 'red', 1e6, 'blue']
然后,您遍历视口中的每个要素以实际添加该属性:
Then you iterate over every feature within the viewport to actually add that attribute:
for (const district of districts) {
map.setFeatureState({ source: 'mysource', sourceLayer: 'mysourcelayer', id: district.id }, { population: district.population});
}
请参见 https://docs.mapbox.com /mapbox-gl-js/api/map/#map#setfeaturestate .
这篇关于Mapbox GL JS:在大型GeoJSON中为单个功能着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!