首页 > 解决方案 > 带有 React-leaflet version3 的传单地图上的自定义按钮

问题描述

我是 React 打字稿的新传单学习者。想要在地图上创建自定义按钮。单击按钮时,将出现一个弹出窗口。我看到了很多例子,但它们都是基于旧版本的,我也尝试创建自己的但没有运气。该文档也没有提供太多帮助。即使是功能性自定义控件组件对我的应用程序也非常有效。对此的任何帮助将不胜感激。这是我的代码,

自定义按钮

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

class Description extends React.Component<{props: any}> {
  createButtonControl() {
    const MapHelp = L.Control.extend({
      onAdd: (map : Map) => {
        const helpDiv = L.DomUtil.create("button", ""); //how to pass here the button name and
        //other property ?
        
        //a bit clueless how to add a click event listener to this button and then
        // open a popup div on the map

      }
     
    });
    return new MapHelp({ position: "bottomright" });
  }

  componentDidMount() {
    const { map } = this.props as any;
    const control = this.createButtonControl();
    control.addTo(map);
  }

  render() {
    return null;
  }
}

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

export default withMap(Description);

我想这样称呼它

<MapContainer
        center={defaultPosition}
        zoom={6}
        zoomControl={false}
        >
             <Description />
            

             <TileLayer
                attribution="Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL."
                url="https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png"
            />
            <ZoomControl position={'topright'}/>
        </MapContainer>

标签: reactjstypescriptleafletopenstreetmapreact-leaflet

解决方案


你很近。坚持使用类组件,您只需要继续创建按钮实例。你可以使用一个道具Description来确定你的按钮会说什么和做什么:

      <Description
        title={"My Button Title"}
        markerPosition={[20.27, -157]}
        description="This is a custom description!"
      />

在你的描述中createButtonControl,你快到了。你只需要填写一点:

createButtonControl() {
    const MapHelp = L.Control.extend({
      onAdd: (map) => {
        const helpDiv = L.DomUtil.create("button", "");
        this.helpDiv = helpDiv;
        // set the inner content from the props
        helpDiv.innerHTML = this.props.title;

        // add the event listener that will create a marker on the map
        helpDiv.addEventListener("click", () => {
          console.log(map.getCenter());
          const marker = L.marker()
            .setLatLng(this.props.markerPosition)
            .bindPopup(this.props.description)
            .addTo(map);

          marker.openPopup();
        });
 
        // return the button div
        return helpDiv;
      }
    });
    return new MapHelp({ position: "bottomright" });
  }

工作代码框

有一百万种方法可以改变这一点,但希望这会让你继续前进。


推荐阅读