【问题标题】:Leaflet.PolylineMeasure doesn't work in new environmentLeaflet.PolylineMeasure 在新环境中不起作用
【发布时间】:2019-12-26 16:38:20
【问题描述】:

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

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

【问题讨论】:

    标签: javascript typescript leaflet geojson react-leaflet


    【解决方案1】:

    我不确定错误是什么,因为您没有提供任何代码,但是这里是使用 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);
      }
    } 
    

    然后在 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/传单
    2. @types/反应
    3. @types/react-dom
    4. @types/react-leaflet

    更多详情请查看demo

    【讨论】:

    • 它有帮助!我很高兴地意识到世界上有人愿意提供高质量的帮助(有例子!)谢谢你 kboul - 你已经解决了我的头痛
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多