Search code examples
react-google-maps

react-google-maps: how to use fitBounds API in the parent component


I reproduce my issue in this live demo: https://codesandbox.io/s/p3yv83o7x7

Simple speaking, in the following code:

class MapWrapper extends React.Component {
  constructor() {
    super();
    this.state = {
      zoom: 8,
      strictMode: false
    };
    this.mapRef = null;

    this.onMapMounted = this.onMapMounted.bind(this);
    this.setZoom = this.setZoom.bind(this);
    this.setStrictMode = this.setStrictMode.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  setZoom() {
    this.setState({ zoom: this.mapRef.getZoom() });
  }

  onMapMounted(ref) {
    this.mapRef = ref;
  }

  setStrictMode(e) {
    this.setState({ strictMode: e.target.checked });
  }

  handleClick() {
    // Here I want the map fit a new bound
    // With mapRef reference I can call fitBounds, it ok
    // But how I can create a new bounds object with new google.map.LatLngBounds()?
    // how I can access google lib here?
    //this.mapRef.fitBounds()
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>abc</button>
        <MyMapComponent
          isMarkerShown={this.state.zoom < 10}
          onZoomChanged={this.setZoom}
          onMapMounted={this.onMapMounted}
          zoom={this.state.zoom}
        />
      </div>
    );
  }
}

my confusing point is marked in the handleClick function as comment. In this callback function, I want to use the google map mapRef reference to call fitBounds API. But in order to run this API, I need to make a new LatLngBounds object with new google.map.LatLngBounds(). But how I can access google lib in the parent component? That's my confusing point


Solution

  • Try creating a new LatLngBounds object with new window.google.map.LatLngBounds()