react-map-gl使用多个数据源时,其中一个会变为不可见状态。

8
我在ReactMapGL下指定了两个<Source>元素,尝试加载两个具有不同颜色的不同FeatureCollection。当两个Source同时存在时,它无法工作,因为它隐藏了第一个(id:maps-with-yield)并显示后一个(id:maps-without-yield)。

对于第一个Source也打印出以下警告。

TypeError: Cannot read property 'fill-color' of undefined

我们不能使用多个来源吗?还是我在这里做错了什么?

<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>

注意:属性 yield 总是可用的,因为我已经打印了 mapmapWithoutYield 数据集并进行了检查。

尝试使用相同的源和层,并根据数据类型修改功能。 - Dani Andújar
2个回答

3
根据我的经验,react-map-gl可以使用多个数据源。这里的问题很可能是给不同图层分配的ID。
即使来自不同的数据源,您仍应为每个单独的图层分配唯一的id,以便Mapbox能够识别它们,并使未来的开发更加容易(例如,设置活动图层)。
相同的id"data")将导致第二个图层覆盖第一个图层,这就是为什么maps-with-yield图层的fill-color属性无法读取的原因。

0

我遇到了这个问题,问题在于我在两个不同的层中使用了相同的id,正如Ethan所描述的那样。我按照GeoJSON代码示例进行操作,所以我有以下内容:

    const boundaryStyle = {
        'id': 'data',
        'type': 'line',
        'paint': {
            'line-color': "#f00"
        }
    }
    const protectedSegmentStyle = {
        'id': 'data',
        'type': 'line',
        'paint': {
            'line-color': "#00f",
            'line-width': 2
        }
    }

然后对于图层,我有以下内容:

          <Source type="geojson" data={protectedSegments}>
            <Layer {...protectedSegmentStyle} />
          </Source>
          <Source type="geojson" data={boundaries}>
            <Layer {...boundaryStyle} />
          </Source>

当然,这是在为两个图层提供相同的dataid的情况下进行的,因为样式对象被spread到标记中作为参数。因此,一旦我在我的样式字典中提供了唯一的id,两个图层就会出现。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接