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

如何为react-map-gl多边形绘制器预加载GeoJSON数据?

问题:react-map-gl中MapBoxDraw预加载GeoJSON数据报错

我正在研究react-map-gl的多边形绘制器示例,想实现给MapBoxDraw预加载一批GeoJSON数据,让这些多边形支持编辑。

当前尝试的代码如下:

PolygonControl.tsx

import { useCallback, useEffect } from 'react'

import { useGeoMap } from '../../provider/GeoMapProvider'
import DrawControl from './components/DrawControl'
import { ChangeEvent } from './utils/Polygon.props'

export const PolygonControl = () => {
  const { mode, features, setFeatures } = useGeoMap()

  const onUpdate = useCallback((e: ChangeEvent) => {
    console.log('onUpdate', e.features)
    setFeatures((currFeatures) => {
      const newFeatures = { ...currFeatures }
      for (const f of e.features) {
        newFeatures[f.id] = f
      }
      return newFeatures
    })
  }, [])

  const onDelete = useCallback((e: ChangeEvent) => {
    setFeatures((currFeatures) => {
      const newFeatures = { ...currFeatures }
      for (const f of e.features) {
        delete newFeatures[f.id]
      }
      return newFeatures
    })
  }, [])

  return (
    <>
      {mode.type === 'polygon' && (
        <DrawControl
          position="top-right"
          displayControlsDefault={false}
          defaultMode="draw_polygon"
          controls={{
            polygon: true,
            trash: true,
          }}
          // 传入预加载的多边形数据
          initialPolygons={features}
          onCreate={onUpdate}
          onUpdate={onUpdate}
          onDelete={onDelete}
        />
      )}
    </>
  )
}

DrawControl.tsx

import MapboxDraw from '@mapbox/mapbox-gl-draw'
import { useControl } from 'react-map-gl'

import { DrawPolygonControlProps } from '../utils/Polygon.props'

export default function DrawControl(props: DrawPolygonControlProps) {
  useControl<MapboxDraw>(
    () => {
      const draw = new MapboxDraw(props)

      // 添加预加载的多边形
      if (props.initialPolygons) {
        Object.values(props.initialPolygons).forEach((feature) => {
          draw.add(feature)
        })
      }

      return draw
    },
    ({ map }) => {
      map.on('draw.create', props.onCreate)
      map.on('draw.update', props.onUpdate)
      map.on('draw.delete', props.onDelete)
    },
    ({ map }) => {
      map.off('draw.create', props.onCreate)
      map.off('draw.update', props.onUpdate)
      map.off('draw.delete', props.onDelete)
    },
    {
      position: props.position,
    },
  )

  return null
}

调用draw.add时出现错误:TypeError: Cannot read properties of undefined (reading 'get')。想确认该预加载功能是否可行,以及如何解决这个报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:55:20