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

react-map-gl多Source元素导致其一不可见问题求助

ReactMapGL多Source元素导致第一个被隐藏且报错的问题

我在ReactMapGL中添加了两个<Source>元素,分别加载不同的FeatureCollection并设置不同的填充颜色,但遇到了两个问题:

  1. 当两个Source同时存在时,第一个(id: maps-with-yield)会被隐藏,只显示第二个(id: maps-without-yield)
  2. 第一个Source还会抛出警告:TypeError: Cannot read property 'fill-color' of undefined

我已经确认过map和mapWithoutYield两个数据集的yield属性始终存在,想知道是ReactMapGL不允许使用多个Source,还是我的操作哪里出错了?

我的代码如下:

<MapGL {...viewport} mapboxApiAccessToken={accessToken} onViewportChange={viewport => setViewport(viewport)} onHover={onHover} onClick={onClick} onLoad={onLoad} width="100%" height="100%" scrollZoom={false} dragRotate={false} touchRotate={false} keyboard={false} >
{map && map.features.length > 0 ? (
<Source id="maps-with-yield" type="geojson" data={map}>
<Layer id="data" type="fill" paint={{ 'fill-color': { property: 'yield', stops: [ [minYield, worstYieldColor], [maxYield, bestYieldColor] ] }, 'fill-outline-color': '#fff' }} />
</Source>
) : null}
{mapWithoutYield && mapWithoutYield.features.length > 0 ? (
<Source id="maps-without-yield" type="geojson" data={mapWithoutYield}>
<Layer id="data" type="fill" paint={{ 'fill-color': '#66AEEC', 'fill-outline-color': '#fff' }} />
</Source>
) : null}
</MapGL>

问题原因

你遇到的核心问题是两个Layer的id重复了!Mapbox GL的Layer id是全局唯一的——当第二个Layer(来自maps-without-yield的Source)加载时,它会直接覆盖第一个同名的Layer,这就导致第一个Source的Layer被隐藏;同时因为第一个Layer被覆盖,相关的paint配置找不到对应的Layer实例,就抛出了fill-color未定义的错误。

解决方案

只需要给两个Layer设置不同的唯一id即可,比如把第一个Layer的id改成data-with-yield,第二个改成data-without-yield:

修改后的代码片段:

<MapGL {...viewport} mapboxApiAccessToken={accessToken} onViewportChange={viewport => setViewport(viewport)} onHover={onHover} onClick={onClick} onLoad={onLoad} width="100%" height="100%" scrollZoom={false} dragRotate={false} touchRotate={false} keyboard={false} >
{map && map.features.length > 0 ? (
<Source id="maps-with-yield" type="geojson" data={map}>
<Layer id="data-with-yield" type="fill" paint={{ 'fill-color': { property: 'yield', stops: [ [minYield, worstYieldColor], [maxYield, bestYieldColor] ] }, 'fill-outline-color': '#fff' }} />
</Source>
) : null}
{mapWithoutYield && mapWithoutYield.features.length > 0 ? (
<Source id="maps-without-yield" type="geojson" data={mapWithoutYield}>
<Layer id="data-without-yield" type="fill" paint={{ 'fill-color': '#66AEEC', 'fill-outline-color': '#fff' }} />
</Source>
) : null}
</MapGL>

补充说明

ReactMapGL完全支持同时使用多个Source,只要满足以下条件:

  • 每个Source的id是唯一的(你已经做到了这一点)
  • 每个Layer的id也是全局唯一的(这是你之前忽略的关键)
  • Layer的配置正确关联到对应的Source(默认Layer会使用父级Source,你的这部分配置没有问题)

修改后,两个Source对应的Layer就能正常显示各自的样式,不会再出现覆盖和报错的情况了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 08:37:48