【问题标题】:React-Leaflet with leaflet.locatecontrol带有 Leaflet.locatecontrol 的 React-Leaflet
【发布时间】:2020-09-28 20:38:41
【问题描述】:

我按照React Locate on map 的回答,在 gatsby 开发模式下一切正常。但是如果我构建我的 gatsby 项目,它会抛出一个 webpack 错误

“WebpackError: TypeError: Object(...) is not a function”。

如果我将代码从 export default withLeaflet(LocateControl);export default withLeaflet(LocateControl); 构建工作,但我在浏览器中得到错误

“类型错误:this.props.leaflet 未定义”

import React, { Component } from "react";
import { withLeaflet } from "react-leaflet";
import Locate from "leaflet.locatecontrol";

class LocateControl extends Component {
  componentDidMount() {
    const { options, startDirectly } = this.props;
    const { map } = this.props.leaflet;

    const lc = new Locate(options);
    lc.addTo(map);

    if (startDirectly) {
      // request location update and set location
      lc.start();
    }
  }
  render() {
    return null;
  }
}
export default withLeaflet(LocateControl);

locate-plugin 应该可以工作,但现在构建不工作。

【问题讨论】:

    标签: gatsby react-leaflet


    【解决方案1】:

    我遇到了同样的问题,几个小时后,这个解决方案对我有用:

    locatecontrol.js

    import { useEffect } from "react";
    import { useLeaflet } from "react-leaflet";
    import Locate from "leaflet.locatecontrol";
    
    export default function LocateControl() {
    
      const { map } = useLeaflet();
    
      useEffect(() => {
    
        // geo locate props
        const locateOptions = {
          position: 'topright',
          maxZoom: 19,
          strings: {
              title: 'Show me where I am, yo!'
          },
          onActivate: () => {} // callback before engine starts retrieving locations
        }
    
        const lc = new Locate(locateOptions);
        // console.log(lc);
        lc.addTo(map);
    
      }, [map]);
    
      return null;
    
    }
    

    导入到 leaflet-map.js

    import LocateControl from "./locatecontrol"
    

    并在地图

    中使用LocateControl
    <Map>
     <LocateControl startDirectly/>
    </Map>
    

    我是 React 新手,我不确定解决方案是否完全正确 - 但我还没有遇到错误(我们会看到 :))并且 gatsby 构建顺利。

    也许有人会想出更好的解决方案。

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2020-06-25
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多