You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mapbox如何动态修改GeoJSON源的cluster属性实现聚合开关功能

Mapbox聚合图层开关功能实现

在使用Mapbox开发时已成功实现聚合图层,如需手动切换聚合功能可参考如下流程:


初始配置代码

创建聚合数据源

const source = {
    type: "geojson",
    data: {
        "type": "FeatureCollection",
        "features": []
    },
    cluster: true,
    clusterRadius: 10
}
this.map.addSource(id, source);

动态更新数据源内容

this.map.getSource(this.id).setData({
    "type": "FeatureCollection",
    "features": this.createInnerCircles()
})

完成上述配置后添加对应的聚合层和圆点图层,即可正常使用聚合功能。


问题说明

需要将数据源的cluster: true属性修改为false时,若采用「修改源配置后移除再重新添加源」的实现方式会触发报错:

Source "test" cannot be removed while layer "test-outer" is using it.

错误原因是数据源被关联图层引用,无法直接移除。


最终实现方案

无需移除数据源和关联图层,直接修改当前地图样式中的数据源配置后重新设置样式即可实现聚合开关:

setCluster(isVisable, clusterRadius = 10) {
    const style = this.map.getStyle()
    style.sources.test.cluster = isVisable;
    if(isVisable) {
        style.sources.test.clusterRadius = clusterRadius;
    }
    this.map.setStyle(style)
}

内容的提问来源于stack exchange,提问作者Johan Hoeksma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:06:05