如何解决带有 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>
解决方法
你很接近。坚持使用类组件,您只需要继续创建按钮实例。您可以使用 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" });
}
Working codesandbox
有一百万种方法可以改变这一点,但希望这能让你继续前进。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。