安装库,导入js,css获取地图引用,然后渲染标记:
import R from "leaflet-responsive-popup";
import "leaflet-responsive-popup/leaflet.responsive.popup.css";
...
const position = [51.505, -0.09];
const mapRef = useRef();
const icon = L.icon({
iconUrl: "https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/dist/images/marker-icon.png",
shadowUrl: "https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/dist/images/marker-shadow.png"
});
useEffect(() => {
const map = mapRef.current.leafletElement;
const marker = L.marker([51.5, -0.09], { icon });
const popup = R.responsivePopup({
hasTip: true,
autoPan: true,
offset: [15, 20]
}).setContent("A pretty CSS3 responsive popup.<br> Easily customizable.");
marker.addTo(map).bindPopup(popup);
}, []);
return (
<Map center={position} ref={mapRef} zoom={13} style={{ height: "100vh" }}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
</Map>
);
Edit要使插件独立于外部包装组件,您可以拥有一个 ResponsivePopup 包装文件:
const ResponsivePopup = () => {
const { map } = useLeaflet();
console.log(map);
useEffect(() => {
const marker = L.marker([51.5, -0.09], { icon });
const popup = R.responsivePopup({
hasTip: true,
autoPan: true,
offset: [15, 20]
}).setContent("A pretty CSS3 responsive popup.<br> Easily customizable.");
marker.addTo(map).bindPopup(popup);
}, []);
return null;
};
这次您将使用react-leaflet库提供的useLeaflet钩子获取地图引用,然后您的操作与第一个解决方案类似。
这次你的地图或应用程序将变成这样:
<Map center={position} zoom={13} style={{ height: "100vh" }}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
// here use your custom wrapper for responsive popup
<ResponsivePopup />
</Map>
Demo https://codesandbox.io/s/using-leaflet-responsive-popup-library-in-react-leaflet-w0909