React-leaflet how to get map bounds and center it?

一笑奈何 提交于 2019-12-14 01:24:09

问题


I want to get this map bounds and center it map
I tried with getBounds() and getCenter() but it was undefined.
then i found this but it says Cannot read property 'leafletElement' of undefined
Thanks for your help in forward.

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:


Seems you forgot to assign ref attribute for a Map component:

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

to get a reference to leaflet instance:

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

Demo



来源:https://stackoverflow.com/questions/51399480/react-leaflet-how-to-get-map-bounds-and-center-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!