集合中的 Mapbox JS 运行时样式

Mapbox JS Runtime Styling from collection

所以我上传了一个 Mapbox Tileset,其中包含美国的人口普查区块信息。 tileset 中的每个几何体都有一个名为 GeoID 的 属性,我正在尝试根据我拥有的另一个集合应用样式。

该集合是具有以下格式的数组对象:[{geoid: string, weight: number}, {geoid: string, weight: number},...]

我想将数组中的 GeoID 与图块集中的图层相匹配,并根据该对象的相应权重 属性 为其着色。权重是一个介于 0 和 1 之间的数字。我尝试从 Mapbox 搜索有关运行时样式和表达式的文档,但我找不到任何关于从集合中推断数据并将其有条件地应用于 tileset 中正确几何的信息。

您可以从您的权重列表生成一个表达式,然后将其传递给您想要设置样式的图层:

const weights = [
    {geoid: 1, weight: 10},
    {geoid: 2, weight: 5},
    {geoid: 3, weight: 30},
];
const cases = weights.map(weight => {
    const condition = ['==', ['get', 'geoid'], weight.geoid];
    const output = getColor(weight.weight);

    return [
        condition,
        output
    ];
});
const expresion = ['case',
    ...cases.reduce((flat, conditionAndOutput) => [...flat, ...conditionAndOutput]),
    '<default-color>'
];

/*
Will result in:
    [
        "case",
        [
        "==",
        [
            "get",
            "geoid"
        ],
        1
        ],
        "rgb(255, 255, 255)",
        [
        "==",
        [
            "get",
            "geoid"
        ],
        2
        ],
        "rgb(255, 255, 255)",
        [
        "==",
        [
            "get",
            "geoid"
        ],
        3
        ],
        "rgb(255, 255, 255)",
        "<default-color>"
    ]
*/