如何使用 React-Leaflet 获取标记集合的边界

cor*_*eyl 2 javascript leaflet reactjs react-leaflet

如何获取标记集合的边界,以便这些边界可用于在react-leaflet地图上显示所有标记?这是我的渲染功能:

render() {
    const position = [51.505, 4.12];

    return (
        <Map center={position} zoom={3} style={{width: '100%', height: '600px'}} >
            <TileLayer
                attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
            />
            {this.state.markers || null}
        </Map>
    );
}
Run Code Online (Sandbox Code Playgroud)

标记添加到this.state.markers

this.state.markers.push(
    <Marker position={position}>
        <Popup>
            <span>Hello</span>
        </Popup>
    </Marker>
);
this.setState({markers: this.state.markers});
Run Code Online (Sandbox Code Playgroud)

标记正在显示,但我希望调整地图的边界和中心,以便标记在具有一定填充量的地图视口内很好地适应。

关于如何做到这一点的任何想法?

编辑:这是我的导入语句:import {Map, Marker, Popup, TileLayer} from 'react-leaflet';

Eva*_*oky 7

您可以向Map 组件添加 bounds 参数。它接受传单 latLngBounds参数。因此,您可以执行以下操作:

import {latLngBounds} from 'leaflet'

...

render () {
  const bounds = latLngBounds([firstCoord, firstCoord])
  markerData.forEach((data) => {
    bounds.extend(data.latLng)
  })

  return (
    <Map bounds={bounds} >
      ...
    </Map>
  )
}
Run Code Online (Sandbox Code Playgroud)