【发布时间】:2021-04-28 21:47:26
【问题描述】:
我有一个 React Leaflet 地图,需要在给定一组标记时更改其中心和缩放。应更改缩放以使所有标记都可见。
当前正在尝试使用函数ChangeView 进行这种视图更改。
使用下面的代码,我可以移动地图视图,但不能让地图适应边界。运行代码会报错:
错误:边界无效。
上线
map.fitBounds(markerBounds)
我们能做什么?谢谢!
import L, { LatLng, latLngBounds, FeatureGroup } from 'leaflet';
import React from 'react';
import { MapContainer, TileLayer, Marker, Popup, useMap } from 'react-leaflet';
import MarkerClusterGroup from 'react-leaflet-markercluster';
import { LatLon, MapMarker } from '../../common/types';
import { config } from '../../config';
interface IProps {
markers: MapMarker[];
searchCenter: LatLon;
}
interface IChangeView {
center: LatLon;
markers: MapMarker[];
}
function ChangeView({ center, markers }: IChangeView) {
const map = useMap();
map.setView({lng: center.lon, lat: center.lat}, DEFAULT_ZOOM);
let markerBounds = latLngBounds([]);
markers.forEach(marker => {
markerBounds.extend([marker.lat, marker.lon])
})
map.fitBounds(markerBounds) // <===== Error: Bounds are not valid.
return null;
}
export function MapView({markers, searchCenter}: IProps): JSX.Element {
return (
<MapContainer
center={[searchCenter.lat, searchCenter.lon]}
zoom=14
style={{ width:'100%', height:'100vh' }}
className='markercluster-map'
>
<ChangeView center={searchCenter} markers={markers} />
<TileLayer
url={`https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=${config.api.mapbox}`}
/>
<MarkerClusterGroup>
{
markers.map((marker, index) => (
<Marker
position={[marker.lat, marker.lon]}
key={index}
/>
))
}
</MarkerClusterGroup>
</MapContainer>
)
}
也尝试使用FeatureGroup 而不是latLngBounds,但它给出了完全相同的错误
错误:边界无效
let group = new FeatureGroup();
markers.forEach(marker => {
L.marker([marker.lat, marker.lon]).addTo(group);
})
map.fitBounds(group.getBounds());
【问题讨论】:
-
你能在
map.fitBounds(markerBounds)之前做一个console.log(markerBounds)吗?那有什么好处?另外,您的markers数组是什么样的?总是有值,还是有时是空的? -
@SethLutske 它有时是空的,这就是问题所在。谢谢!
-
只有当标记数组为空时才会出现此错误?
标签: javascript reactjs typescript leaflet react-leaflet