Leaflet.PolylineMeasure 在新环境中不起作用

Leaflet.PolylineMeasure doesn't work in new environment

我们有一个与 Leafletreact-leaflet 一起工作的项目,我们还使用了一个很棒的工具,叫做 Leaflet.PolylineMeasure 用于测量距离。 主要应用程序基于 babel 和老式 React Classes 并且运行完美! 最近,我们开始使用 TypeScript 开发项目的新部分,并使用 hooks 开发功能组件。 在使用标尺功能时,我发现 Leaflet.PolylineMeasure 在新环境 中不起作用! 根据插件的描述,在添加所需的库后,应该会出现新的 Measurer 函数 L.control.polylineMeasure(options)。但事实并非如此! 在没有 TypeScript、hooks 和相同包版本的 Leaflet 和 Leaflet.PolylineMeasure 的主应用程序中,一切仍然正常! 我尝试将 map 组件重写为 React Class 组件,还尝试 add typings 但它没有帮助。

知道问题的根源是什么吗?

我不确定错误是什么,因为您没有提供任何代码,但是这是使用 react typescript、react-leaflet 的外观。您可以像这样扩展 MapControl 以实现 Leaflet.PolylineMeasure:

class PolylineMeasure extends MapControl {
  createLeafletElement() {
    return (L.control as any).polylineMeasure({
      position: "topleft",
      unit: "metres",
      showBearings: true,
      clearMeasurementsOnStop: false,
      showClearControl: true,
      showUnitControl: true
    });
  }

  componentDidMount() {
    const { map } = this.props.leaflet;
    const polylineMeasure = this.leafletElement;
    polylineMeasure.addTo(map);
  }
} 

然后在地图组件中使用它:

const Leaflet = () => {
  return (
    <Map
      style={{ height: "100vh" }}
      center={[48, 0]}
      zoom={4}
      minZoom={3}
      maxZoom={18}
    >
      <TileLayer
        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?"
      />
      <PolylineMeasure />
    </Map>
  );
};

您需要包含以下库才能避免打字稿错误:

  1. @types/leaflet
  2. @types/react
  3. @types/react-dom
  4. @types/react-传单

有关详细信息,请查看此 demo