将 Leaflet 插件添加到 React-Leaflet

8
我正在尝试在 react-leaflet v2 中创建一个自定义组件,扩展了一个叫做EdgeMarker的 leaflet 插件。然而,文档没有明确说明如何操作。因此,我将 Leaflet.EdgeMarker.js 文件从该仓库中复制并添加到了我的实现中。
到目前为止,我已经完成了以下操作:
import PropTypes from 'prop-types';
import { MapLayer, withLeaflet } from 'react-leaflet';
import L from 'leaflet';
import '../EdgeMarker/EdgeMarker';


class EdgeMarkerComp extends MapLayer{

  static childContextTypes = {
    layerContainer: PropTypes.object
  }

  getChildContext () {
    return {
      layerContainer: this.leafletElement
    }
  }

  createLeafletElement(props) {
    const { options } = props;
    console.log("Options: ", options);
    return new L.EdgeMarker(options);
  }

}

export default withLeaflet(EdgeMarkerComp);

在我的地图上:

const options = {
      icon: L.icon({ // style markers
          iconUrl: 'images/edge-arrow-marker-black.png',
          clickable: true,
          iconSize: [48, 48],
          iconAnchor: [24, 24]
      }),
      rotateIcons: true, 
      layerGroup: null 
};

<Map ...>
  <EdgeMarkerComp options={options} />
</Map>

需要帮忙吗?

2个回答

4

我最终通过直接使用地图来解决问题。这样做更方便,可以在向地图添加交互时给我更多的自由。只需按照以下方式定义您的地图并使用地图引用执行任何操作:

<Map
  ref={Map => this.map = Map}
  ...
  >
  ...
<Map>

现在你可以使用由react-leaflet定义的this.map.leafletElement在任何leaflet对象中引用地图:
const polyline = L.polyline([p1,p2 ], {color: 'yellow'}).addTo(this.map.leafletElement);

上面的代码将在地图上添加一个新的行。

polyline.remove(); => 将从地图中移除该行。


你好,能否提供一个react-leaflet v2正常工作的示例链接吗? - Roger Veciana

0

是的,使用 react-leaflet 的 v1.x 版本时非常简单明了。

我遇到了类似的扩展问题,并在 react-leaflet 的 github 存储库上开了一个问题,希望 Paul 能为我们指引方向。 https://github.com/PaulLeCam/react-leaflet/issues/506

目前,降级到 v1.9 对我来说是可行的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接