[英]How to use getBounds() to get pick up map ends with react-leaflet?
How to get the 4 coordinates that represent the 4 ends visible on the map using react-leaflet
.如何使用
react-leaflet
获取表示 map 上可见的 4 个末端的 4 个坐标。
I would like to use the contains()
function to return true or false for a coordinate that is passed, if it is true it means that it is within the limits established in getBounds()
, if it is false it is outside.我想使用
contains()
function 为传递的坐标返回 true 或 false,如果它是 true 则意味着它在getBounds()
中建立的限制内,如果它是 false 它在外面。
Just wiht leaflet
in pure JavaScript I know how to use this function. But I'm developing a React Web Application, and I'm using react-leaflet
library and need use this function.就在纯
leaflet
中的 leaflet 我知道如何使用这个 function。但是我正在开发一个 React Web 应用程序,我正在使用react-leaflet
库并且需要使用这个 function。
Thank you in advance for any help.预先感谢您的任何帮助。
Here's my code I put into codesandbox这是我放入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='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> </Map> ); }; export default App;
You need to get a reference to the map. Then you can access the ref's .leafletElement
property, which is the map instance:您需要获得对 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>
);
};
You need a reference to the map, so that you can call things like L.map.getBounds()
.您需要对 map 的引用,以便您可以调用
L.map.getBounds()
类的东西。 react-leaflet no longer uses the .leafletElement
property since react-leaflet v3. react-leaflet 从 react-leaflet v3 开始不再使用
.leafletElement
属性。 Here's a v4 answer:这是一个 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>
);
};
The docs have some examples of how to grab the underlying L.map instance as a ref and use it, here: https://react-leaflet.js.org/docs/example-external-state/ .文档有一些示例,说明如何获取底层 L.map 实例作为引用并使用它,此处: https://react-leaflet.js.org/docs/example-external-state/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.