react-google-maps: как использовать API fitBounds в родительском компоненте

Я воспроизвожу свою проблему в этой живой демонстрации: https://codesandbox.io/s/p3yv83o7x7

Проще говоря, в следующем коде:

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>
    );
  }
}

мой запутанный момент отмечен в функции handleClick как комментарий. В этой функции обратного вызова я хочу использовать ссылку mapRef карты Google для вызова fitBounds API. Но чтобы запустить этот API, мне нужно создать новый объект LatLngBounds с new google.map.LatLngBounds(). Но как я могу получить доступ к google lib в родительском компоненте? Это мой сбивающий с толку момент


person Chris Bao    schedule 25.10.2018    source источник


Ответы (1)


Попробуйте создать новый объект LatLngBounds с помощью new window.google.map.LatLngBounds()

person Aonan Li    schedule 26.10.2018