【问题标题】:Is there a way to make a leaflet popup responsive using react-leaflet library?有没有办法使用 react-leaflet 库使传单弹出响应响应?
【发布时间】:2020-04-04 19:53:09
【问题描述】:

我一直在研究,我知道leafletjs 有插件https://github.com/yafred/leaflet-responsive-popup,但我需要一个解决方法来解决我正在使用的库react-leaflet

react-leaflet 有很多第三方插件,但我没有看到任何适合我的插件。 如果有人知道如何或做过类似的事情,如果你能分享它会很酷。我很难受。

谢谢。

【问题讨论】:

  • 所以你想在 react 上集成 leaflet-responsive-popup 也使用 react-leaflet。对吗?
  • 是的!没错。

标签: javascript reactjs leaflet popup react-leaflet


【解决方案1】:

安装库,导入js,css获取地图引用然后渲染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='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
    </Map>
  );

编辑 要使插件独立于外部包装器组件,您可以拥有一个 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='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      // here use your custom wrapper for responsive popup
      <ResponsivePopup />
    </Map>

Demo

【讨论】:

  • 太好了,这行得通,但我想知道是否有办法将leaflet-responsive-popup 定义为react 元素而不是使用javascript。像 而不是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 2013-01-11
  • 2011-11-30
  • 2022-12-08
  • 2017-02-22
  • 1970-01-01
相关资源
最近更新 更多