我正在建立一个在 map 上呈现圆圈的网站。如果 ["feature-state", "value"]
属性 >= 1,则圆圈为绿色,如果 ["feature-state", "value"]
属性为 0 或 null,圆圈为红色(默认值为 0)。当我的 map 放大到足够大时,圆圈会正确渲染(所有带有 ["feature-state", "value]
>= 1 呈绿色)。但是,当我缩小时,包含带有 ["feature-state", "value]
的子特征/圆圈的簇圆圈,该圆圈呈现为红色而不是绿色。有什么办法确保如果其子项 ["feature-state", "value]
的总和 >= 1,则簇呈现为绿色?
下面是我的渲染代码:
map.addSource('cities', {
"type": "geojson",
"data": "cities.geojson",
"cluster": true,
"clusterMaxZoom": 14,
"clusterRadius": 80
});
map.addLayer({
"id": "cities",
"type": "circle",
"source": "cities",
"paint": {
"circle-color": [
"case",
["==", ["feature-state", "value"], null], "#ff4d4d",
[">=", ["feature-state", "value"], 1], "#33cc33",
"#ff4d4d"
],
"circle-radius": [
"case",
["==", ["feature-state", "value"], null], 9,
[">=", ["feature-state", "value"], 1], 12,
6
],
"circle-opacity" : [
"case",
["==", ["feature-state", "value"], null], 0.7,
[">=", ["feature-state", "value"], 1], 1,
0.7
]
},
});
下面是我设置“feature-state”
的方法:
map.setFeatureState({source: "cities", id : 124312}, {value: 1});
最佳答案
这可以通过源对象的 clusterProperties
选项来完成,该选项采用自定义表达式来聚合聚类点的属性。
注意:clusterProperties
选项不支持功能状态聚合,只能使用属性。我将在下面的步骤中解释它,底部还附有一个 codepen 示例。
- 首先,定义一个表达式,用于聚合形成聚类的要素属性。
{
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 80,
clusterProperties: {
/*
get the property numUser, then cast it to number or 0,
then sum it, then store the sum as cluster's numUser property
*/
numUsers: ["+", ["number", ["get", "numUsers"], 0]]
},
type: "geojson",
data: geojson,
}
- 更新样式表达式以使用功能属性而不是
功能状态
:
paint: {
"circle-color": [
"case",
["==", ["get", "numUsers"], null], "#ff4d4d",
[">=", ["get", "numUsers"], 1], "#33cc33",
"#ff4d4d"
],
"circle-radius": [
"case",
["==", ["get", "numUsers"], null], 9,
[">=", ["get", "numUsers"], 1], 12,
6
],
"circle-opacity": [
"case",
["==", ["get", "numUsers"], null], 0.7,
[">=", ["get", "numUsers"], 1], 1,
0.7
]
}
- 更新 GeoJSON 属性:
// Update after 2 seconds
setTimeout(() => {
const newGeojson = {
...geojson,
features: geojson.features.map(feature => {
if ([0, 1].includes(feature.id)) { // update features selectively
feature.properties.numUsers = 1;
}
return feature;
})
};
map.getSource('geom').setData(newGeojson);
}, 2000);
这是一个有效的代码笔:https://codepen.io/manishraj/full/wvwmNKR
这里有一个相关的例子,来自mapbox:https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/
关于javascript - Mapbox GL JS : Clustering circle not rendered properly upon zooming out,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875884/