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

OpenLayers 8.1.0中用case表达式设置图标颜色报错求助

OpenLayers 8.1.0 图标颜色表达式错误修复

问题场景

使用OpenLayers 8.1.0时,尝试通过case表达式根据图层属性roche修改图标颜色,icon-src正常生效,但icon-color抛出错误:

Uncaught Error: Expected an array of numbers for icon-color

原代码如下:

const marqueursTest = new ol.layer.Vector({
  name: 'marqueursTest',
  zIndex: 999,
  visible: true,
  source: sourceWFS,
  style: { 
          'icon-src': 'assets/cavage.png',
          'icon-color': [
            'case',
            ['==', ['get', 'roche'], 'calcaire'], [255,153,102],
            ['==', ['get', 'roche'], 'craie'], [255,230,72],
            ['==', ['get', 'roche'], 'gypse'], [153,255,102],
            ['==', ['get', 'roche'], 'autre'], [102,204,255],
            [226, 226, 0],
          ],        
  },
  opacity: 1    
});

问题原因

你误用了颜色表达式的写法:icon-color的case分支结果不能直接传数字数组,必须用OpenLayers的颜色表达式函数(rgb或rgba)包裹。直接写数字数组会被识别为普通数组,而非颜色值,导致类型匹配错误。

修正后的代码

const marqueursTest = new ol.layer.Vector({
  name: 'marqueursTest',
  zIndex: 999,
  visible: true,
  source: sourceWFS,
  style: { 
          'icon-src': 'assets/cavage.png',
          'icon-color': [
            'case',
            ['==', ['get', 'roche'], 'calcaire'], ['rgb', 255, 153, 102],
            ['==', ['get', 'roche'], 'craie'], ['rgb', 255, 230, 72],
            ['==', ['get', 'roche'], 'gypse'], ['rgb', 153, 255, 102],
            ['==', ['get', 'roche'], 'autre'], ['rgb', 102, 204, 255],
            ['rgb', 226, 226, 0],
          ],        
  },
  opacity: 1    
});

说明

  • 所有颜色值都需要用['rgb', r, g, b]或['rgba', r, g, b, a]的表达式格式传递,符合OpenLayers样式表达式对颜色类型的要求。
  • 如果需要透明度,可以改用rgba表达式,比如['rgba', 255,153,102, 0.8]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 15:26:08