我有一个将多边形动态添加到Mapbox图层的应用程序。我正在使用匹配表达式来设置多边形填充的样式,但是在用数组输入来确定表达式的语法时遇到了问题。
这是我尝试做的一个简单示例:https://angular-bpuswd.stackblitz.io
我有一个具有要素属性states
的图层。我想将每个状态与不同的填充颜色相关联,每个this official mapbox example for data-driven styles:
// want to match New York to color #F0F and Pennsylvania to color #FF0
const states = ['New York', 'Pennsylvania'];
const colors = ['#F0F', '#FF0'];
const statesAndColors = ['New York', '#F0F', 'Pennsylvania', '#FF0'];
this.map.addLayer({
id: 'states',
type: 'fill',
source: {
type: 'geojson',
data: POLYGONS,
},
paint: {
// doesn't work
'fill-color': ['match', ['string', ['get', 'state']], states, colors, '#AAAAAA']
// also doesn't work
// 'fill-color': ['match', ['string', ['get', 'state']], statesAndColors, '#AAAAAA']
// below example works
// 'fill-color': ['match', ['string', ['get', 'state']], 'New York', '#F0F', 'Pennsylvania', '#FF0', '#AAAAAA']
}
});
mapbox expression match文档指出,您可以使用'个文字值数组,其值必须是所有字符串或所有数字(例如[100,101]或[“ c”,“ b”])。如果数组中的任何值匹配,则输入匹配,类似于不推荐使用的“ in”运算符。'
但是上面的示例无法正常工作。如何格式化表达式以这些样式读取为数组? (注意:此示例应用程序可以使用直接匹配,因为纽约和宾夕法尼亚州的值是硬编码的,但是我的实际应用程序具有动态上传的多边形,因此它们在运行时是未知的。)
这里的问题只是Javascript语法问题。 statesAndColors
是一个数组,而您需要传入数组的各个值。您可以使用扩展运算符(...
)进行此操作。
因此,更改此:
'fill-color': ['match', ['string', ['get', 'state']], statesAndColors, '#AAAAAA']
对此:
'fill-color': ['match', ['string', ['get', 'state']], ...statesAndColors, '#AAAAAA']
((来源:我实际上在您引用的文档中写了这句话:))