Mat*_*ton 3 javascript leaflet reactjs react-leaflet
我有以下功能反应组件,它可以在“边界”框中正确显示两个静态标记,该框适合两个标记。
我希望能够传递一系列纬度和经度值以供地图显示,但我不知道如何做到这一点。
这是工作的静态示例:
import React from 'react'
import { MapContainer, TileLayer, Marker } from 'react-leaflet'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
const MapLeaflet = () => {
// STATIC MARKER POSITIONS
const position = [42.2974279, -85.628292];
const position2 = [-8.852507, -45.351563];
// BOUNDS CODE
const bounds = L.latLngBounds([position, position2]);
return (
<MapContainer
className=" map"
center={position}
bounds={bounds}
>
<Marker key={key} position={position}>
<Heart/>
</Marker>
<Marker key={key} position={position2}>
<Heart/>
</Marker>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
)
}
Run Code Online (Sandbox Code Playgroud)
如果我传递 is {coords} 我就可以动态显示标记:
const MapLeaflet = ({coors}) => {
...
{ coords && coords.map(coord => (
<Marker key={key} latitude={coord[0]} longitude={coord[1]}>
<SomeMarker/>
</Marker>
))}
...
}
Run Code Online (Sandbox Code Playgroud)
但显然,地图尚未将这些“坐标”考虑到边界。传入的coords数组的console.log输出如下:
0: (2) [51.52167056034225, -0.12894469488176763]
1: (2) [46.58635156377568, 2.1796793230151184]
2: (2) [40.819721, 14.341111]
Run Code Online (Sandbox Code Playgroud)
不知何故,我需要以代码接受的格式将以下行替换为对传入坐标的引用,但我不知道该怎么做。
const bounds = L.latLngBounds([position, position2]);
Run Code Online (Sandbox Code Playgroud)
类似的东西
const bounds = L.latLngBounds({coords});
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激。
亲切的问候,马特
我想我明白你想要实现的目标。
maxBounds 在react-leaflet v.3 中是不可变的,因此您需要创建一个自定义组件,该组件将在坐标更改时更改地图边界。它将以坐标为道具,当坐标改变或游戏着陆时,它会改变地图边界。
function Bounds({ coords }) {
const map = useMap();
useEffect(() => {
if (!map) return;
map.fitBounds(coords);
}, [map, coords]);
return null;
}
Run Code Online (Sandbox Code Playgroud)
在您的应用程序组件中,我包含了边界更改(坐标变量)并且地图边界相应更改的情况。希望这就是您正在寻找的。
function App() {
const [coords, setCoords] = useState([
[51.52167056034225, -0.12894469488176763],
[46.58635156377568, 2.1796793230151184],
[40.819721, 14.341111]
]);
return (
<>
<MapLeaflet coords={coords} />
<button
onClick={() =>
setCoords([
[52.52167056034225, -0.12894469488176763],
[47.58635156377568, 2.1796793230151184],
[41.819721, 14.341111]
])
}
>
Change coords
</button>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1701 次 |
| 最近记录: |