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

时间:2018-07-18 10:18:59

标签: react-leaflet

我想获得此地图边界并居中 map
我尝试使用getBounds()和getCenter()进行操作,但未定义。
然后我发现了它,但是它说无法读取未定义的属性“ 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 个答案:

答案 0 :(得分:1)

似乎您忘记为ref组件分配Map属性:

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

获取对传单实例的引用:

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

Demo

相关问题