使用 React Leaflet V3 创建自定义层

时间:2021-07-17 18:23:24

标签: typescript leaflet openstreetmap react-leaflet react-leaflet-v3

我想通过单击按钮或将鼠标悬停在按钮上,在地图上创建自定义辅助 div 层。该按钮也是地图上的自定义控件按钮。这是示例 control button

我的自定义图层将提供地图相关信息。整个功能应该像 React 传单 Layers control,

也就是说,在鼠标悬停/单击自定义控件 div/按钮时,自定义图层应弹出与地图相关的信息。

我创建了自定义 div 层。但是,我面临两个问题。

  1. 我无法在地图上定位它。我首先尝试使用“bottomleft”选项。它没有用。我的实际意图是像 React.leaflet 文档中的“图层控制”一样放置在帮助控制按钮附近。
  2. 现在,代码正在侦听地图上的任何“点击”事件。我想让它特定于我的控制按钮。控制层和控制按钮之间如何建立连接?如何将此控制按钮传递给图层?

非常感谢任何帮助。这是我的代码如下。

<块引用>

自定义图层组件

<input type="date" id="date">
<块引用>

暂时是这样称呼的,

import React, { Component } from "react";
import { useMap } from "react-leaflet";
import L, { LeafletMouseEvent, Map } from "leaflet";

class CustomMapHelpGuide extends React.Component<{},{props:any}>{

helpDesc:any;
createDescLayer(opts:any){
    const DescHelp = L.Layer.extend({
        onAdd: (map: Map) => {
            const helpDesc = L.DomUtil.create('div','');
            helpDesc.innerHTML = "this is a map description div";
            this.helpDesc = helpDesc;
            map.getPanes().overlayPane.appendChild(this.helpDesc);
            map.on('click',this.testFunc, this);
            return helpDesc;
        }
    });

    return new DescHelp(); //I tried to pass the "opts" parameter but it is throwing error saying it doesn't expect an argument
}

testFunc(){
    console.log("layer is implemenetd"); //upon click anywhere in the map this is getting printed on console
    
}

componentDidMount() {
    const { map} = this.props as any;
    const layer = this.createDescLayer({ position: 'bottomleft' });
   // map.addLayer(layer);
    layer.addTo(map);
}

componentWillUnmount() {
    this.helpDesc.remove();
  }

  render() {
    return null;
  }
}

function withMap(Component : any) {
  return function WrappedComponent(props : any) {
    const map = useMap();
    return <Component {...props} map={map} />;
  };
}

export default withMap(CustomMapHelpGuide);

0 个答案:

没有答案