【问题标题】:React Leaflet Bound not working as expectedReact Leaflet Bound 未按预期工作
【发布时间】:2021-10-14 07:02:35
【问题描述】:

我正在使用react-leaflet 包从选定的标记在地图上创建绑定动画,如下面的屏幕截图所示。

这里是完整代码:https://codesandbox.io/s/react-leaflet-marker-with-bound-869mj

如果只有选定的标记发生变化,地图将被绑定。

我尝试从此处https://react-leaflet.js.org/docs/example-view-bounds/ 的文档中实现绑定动画示例代码

正如我们从上面的屏幕截图中看到的那样,地图、标记、矩形和面板(右上角)正在显示并且工作正常。

但是如果我们改变选中的标记(通过面板),绑定的动画就不能正常工作(没有显示所有的标记)。

如果我们清空选定的标记(面板中没有选择标记),应用程序会崩溃并产生 错误 Cannot read properties of undefined (reading 'lat')

所以,我的问题是:

  1. 怎么会这样?
  2. 解决办法是什么?

【问题讨论】:

    标签: javascript reactjs leaflet react-leaflet


    【解决方案1】:

    错误Cannot read properties of undefined (reading 'lat') 是因为您将一个空的标记数组传递给<Rectangle>。您至少需要两个标记来定义矩形角,因此请检查您是否至少有两个:

    {/* RECTANGLE */}
    {markerList && markerList.length >= 2 && (
      <Rectangle bounds={markerList} pathOptions={{ color: "red" }} />
    )}
    

    【讨论】:

    • 谢谢,感谢您的回答,但仍然会产生 Bounds are not valid 错误。实际上,我找到了另一种使用 @react-google-maps/api 包来使用边界动画的方法
    【解决方案2】:

    最后,我可以在onCheckboxChange 函数内直接更新边界(位置列表)的最新值后执行此操作。 所以不再需要带有selectedPlacesuseEffect 钩子了。

    const onCheckboxChange = (inputIndex) => {
      let newPlaces = [...selectedPlaces];
      newPlaces[inputIndex].selected = !newPlaces[inputIndex].selected;
      setSelectedPlaces(newPlaces);
    
      let newBounds = selectedPlaces.filter((item) => item.selected);
      newBounds = newBounds.map((item) => item.location);
      setBounds(newBounds);
      map.fitBounds(newBounds);
    };
    
    useEffect(() => {
      map.fitBounds(initialBounds);
    }, []);
    

    这是工作演示:https://codesandbox.io/s/learn-react-leaflet-cnk8tm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2018-05-05
      • 2019-09-27
      相关资源
      最近更新 更多