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

Dre*_*ord 3 javascript geojson mapbox-gl-js

我有一张州地图,每个区域都作为 Mapbox 中的一个单独特征。我想根据政党选票之间的差异更改每个选区的颜色。 这是我正在努力实现的目标我现在拥有的目标的示例

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

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

我该如何解决这个问题,或者还有其他方法吗?

Ste*_*ett 5

所以,你想做数据驱动的样式。基本上有三种方法。

表达式映射属性到颜色

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

'fill-color': ['interpolate-hcl', ['linear'], ['get', 'population'], 0, 'red', 1e6, 'blue']
Run Code Online (Sandbox Code Playgroud)

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

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

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

'fill-color': ['match', ['get', 'id'],
  1020, 'red',
  1033, 'green',
  1038, 'red',
  1049, 'white',
  // ...
Run Code Online (Sandbox Code Playgroud)

使用功能状态在运行时添加属性

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

你的风格是这样的:

'fill-color': ['interpolate-hcl', ['linear'], ['feature-state', 'population'], 0, 'red', 1e6, 'blue']
Run Code Online (Sandbox Code Playgroud)

然后遍历视口中的每个要素以实际添加该属性:

for (const district of districts) {
  map.setFeatureState({ source: 'mysource', sourceLayer: 'mysourcelayer', id: district.id }, { population: district.population});
}
Run Code Online (Sandbox Code Playgroud)

请参阅https://docs.mapbox.com/mapbox-gl-js/api/map/#map#setfeaturestate