问题
I've been researching and I know leafletjs has the plugin https://github.com/yafred/leaflet-responsive-popup but I need a workaround for the library I'm using react-leaflet.
The react-leaflet has a lot of third-party plugins but I don't see anything that works for me. If someone knows how or has done something like this it would be cool if you could share it. I'm having a hard time with this.
Thanks.
回答1:
Install the library, import js, css get a map reference and then render the marker:
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/leaflet@1.6/dist/images/marker-icon.png",
shadowUrl: "https://unpkg.com/leaflet@1.5.0/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 To have the plugin independent in an external wrapper component you can have a ResponsivePopup wrapper file:
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;
};
in which this time you will get the map reference using the useLeaflet hook provided by react-leaflet library and then you act similarly with the first solution. This time your Map or App comp will become like this:
<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://stackoverflow.com/questions/60925036/is-there-a-way-to-make-a-leaflet-popup-responsive-using-react-leaflet-library