簡體   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