简体   繁体   English

如何设置 Leaflet 地图的缩放以显示 React Leaflet 中的所有标记?

[英]How to Set Leaflet Map's Zoom to Show All Markers in React Leaflet?

I have a React Leaflet map that needs to change its center and zoom when given a set of markers.我有一个 React Leaflet map 需要在给定一组标记时更改其中心和缩放。 The zoom should be changed such that all the markers are visible.应更改缩放以使所有标记都可见。

This change of view is currently being attempted using the function ChangeView .目前正在尝试使用 function ChangeView进行这种视图更改。

Using my code below, I am able to move the map view, but not able to let the map fit to the bounds.使用下面的代码,我可以移动 map 视图,但不能让 map 适合边界。 Running the code gives the error:运行代码给出错误:

Error: Bounds are not valid.错误:边界无效。

on the line在线上

map.fitBounds(markerBounds)

What can we do?我们能做什么? Thanks!谢谢!

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>
    )
}

Also tried using FeatureGroup instead of latLngBounds , but it gave the exact same error也尝试使用FeatureGroup而不是latLngBounds ,但它给出了完全相同的错误

Error: Bounds are not valid错误:边界无效

    let group = new FeatureGroup();
    markers.forEach(marker => {
        L.marker([marker.lat, marker.lon]).addTo(group);
    })
    map.fitBounds(group.getBounds());

If the markers array is empty, or null , the bounds you create will not have ._southWest and ._northEast properties, and that error will throw.如果markers数组为空或null ,则您创建的边界将没有._southWest._northEast属性,并且会抛出该错误。 Just make the fitBounds statement conditional on there being markers in the array:只需使fitBounds语句以数组中有标记为条件:

if (markers.length && markers.length > 0){
  markers.forEach(marker => {
    markerBounds.extend([marker.lat, marker.lon])
  })
  map.fitBounds(markerBounds)
}

Or even just a quick one liner:甚至只是一个快速的班轮:

markerBounds.isValid() && map.fitBounds(markerBounds)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM