繁体   English   中英

如何使用 getBounds() 获取 map 以 react-leaflet 结束?

[英]How to use getBounds() to get pick up map ends with react-leaflet?

如何使用react-leaflet获取表示 map 上可见的 4 个末端的 4 个坐标。

我想使用contains() function 为传递的坐标返回 true 或 false,如果它是 true 则意味着它在getBounds()中建立的限制内,如果它是 false 它在外面。

就在纯leaflet中的 leaflet 我知道如何使用这个 function。但是我正在开发一个 React Web 应用程序,我正在使用react-leaflet库并且需要使用这个 function。

预先感谢您的任何帮助。

这是我放入codesandbox的代码

 import React from "react"; import { Map, TileLayer } from "react-leaflet"; import "./styles.css"; const App = () => { const center = [51.505, -0.09]; const [map, setMap] = React.useState(null); React.useEffect(() => { if (map) { const contains = map.getBounds().contains(center); console.log("contains:: ", contains); } }, [center, map]); return ( <Map ref={setMap} style={{ width: "100%", height: "100vh" }} center={center} zoom={13} > <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> </Map> ); }; export default App;

您需要获得对 map 的引用。然后您可以访问 ref 的.leafletElement属性,即 map 实例:

const App = ({ center }) => {
  const mapRef = useRef();

  React.useEffect(() => {
    if (mapRef) {
      const contains = mapRef.leafletElement.getBounds().contains(center);
    }
  }, [center]);

  return (
    <Map 
      ref={mapRef}
      {...otherProps}
    >
      <TileLayer {...props} />
    </Map>
  );
};

工作代码和盒子


react-leaflet v4 的现代答案

您需要对 map 的引用,以便您可以调用L.map.getBounds()类的东西。 react-leaflet 从 react-leaflet v3 开始不再使用.leafletElement属性。 这是一个 v4 答案:

const App = ({ center }) => {
  const [map, setMap] = useState(null)

  React.useEffect(() => {
    if (map) {
      const contains = map.getBounds().contains(center);
    }
  }, [center]);

  return (
    <Map 
      ref={setMap}
      {...otherProps}
    >
      <TileLayer {...props} />
    </Map>
  );
};

文档有一些示例,说明如何获取底层 L.map 实例作为引用并使用它,此处: https://react-leaflet.js.org/docs/example-external-state/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM