我有一个React传单地图,需要在给定一组标记时改变其中心和缩放。缩放应该改变,这样所有的标记都是可见的。
当前正在使用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());
如果markers
数组为空,或null
,则您创建的边界将不具有._southWest
和._northEast
属性,并且该错误将抛出。只要使fitBounds
语句以数组中存在标记为条件:
if (markers.length && markers.length > 0){
markers.forEach(marker => {
markerBounds.extend([marker.lat, marker.lon])
})
map.fitBounds(markerBounds)
}
或者只是简单的一行:
markerBounds.isValid() && map.fitBounds(markerBounds)