React-leaflet如何获取地图边界并将其居中?

7

我想获取这个地图的边界并将其居中 地图
我试过getBounds()和getCenter(),但都是undefined。
后来我发现了这个,但它说无法读取未定义的属性“leafletElement”。
感谢你的帮助。

class FortMap extends Component {
  state = {
    lat: 51.505,
    lng: -0.09,
    zoom: 18,
  }

  componentDidMount(){
    console.log(this.refs.map.leafletElement.getBounds);
  }

  
  render() {
    const { lat , lng , zoom } = this.state;
    const position = [0, 0];

    return (
        <Map center={position} zoom={zoom}>
          <TileLayer
            url={fortniteMap}
            attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
          />
        </Map>
    )
  }
}

export default FortMap;

1个回答

5

看起来您忘记为Map组件分配ref属性:

<Map ref='map' center={position} zoom={zoom}>
  ...
</Map>

获取 Leaflet 实例的引用:

componentDidMount(){
    let mapInst =  this.refs.map.leafletElement;
}

演示


3
"refs is deprecated" 的翻译是:引用已过时。 - Sytham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接