Mapbox GL JS:为大型 GeoJSON 中的单个特征着色

Mapbox GL JS: Coloring individual features in large GeoJSON

我有一张州地图,每个选区都作为 Mapbox 中的一个单独要素。我想根据政党投票之间的差异更改每个选区的颜色。 Here's an example of what I'm trying to achieve versus what I have right now.

我尝试使用 map.setPaintProperty,但是设置一个功能会强制您更改与 ID 不匹配的所有其他功能。

map.setPaintProperty("wisconsin", "fill-color", 
    ["match",["get", "id"],
       features[i].properties["OBJECTID"],
       color, "#ffffff"
    ]
);

我该怎么做,或者有其他方法吗?

所以,您想做 data-driven 造型。基本上就三种方法。

表达式映射 属性 到颜色

如果您想要可视化的属性在数据中(即,您在每个特征上都有一个 .population 属性),您可以使用如下表达式:

'fill-color': ['interpolate-hcl', ['linear'], ['get', 'population'], 0, 'red', 1e6, 'blue']

https://docs.mapbox.com/help/glossary/data-driven-styling/

将每个 ID 映射到特定颜色的表达式

如果您的属性未包含在您的数据源中,您可以通过编程方式生成一个巨大的表达式,如下所示:

'fill-color': ['match', ['get', 'id'],
  1020, 'red',
  1033, 'green',
  1038, 'red',
  1049, 'white',
  // ...

使用feature-state在run-time

添加属性

最后,通过调用 setFeatureState 在运行时实际添加您想要的属性,您可以获得比前一种情况更好的渲染性能,尽管有一些额外的复杂性。

你的风格是这样的:

'fill-color': ['interpolate-hcl', ['linear'], ['feature-state', 'population'], 0, 'red', 1e6, 'blue']

然后迭代视口中的每个功能以实际添加该属性:

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