Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

reactjs - How to get bounds with react-leaflet

I want to get bounds of the current map so that I can search those bounds with the Overpass API.

For leaflet I know the method is just map.getBounds(), but I don't know how to implement that in react-leaflet.

class SimpleExample extends React.Component {
  constructor() {
    super();
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13,
    };
  }

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

  render() {
    const position = [this.state.lat, this.state.lng];
    return (
      <Map center={position} zoom={this.state.zoom} ref='map'>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
      </Map>
    );
  }
}

This is what I've tried. Error says that this.refs.map.getBounds isn't a function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this.refs.map.leafletElement.getBounds.

According to the documentation:

You can directly access the Leaflet element created by a component using this.leafletElement in this component. This leaflet element is usually created in componentWillMount(), except for the Map component where it can only be created after the container is rendered.

which is a round about way of saying they store the leaflet object as leafletElement property on their component objects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...