react-google-maps:如何在父组件中使用fitBounds API

时间:2018-10-25 16:15:35

标签: react-google-maps

我在此现场演示中重现了我的问题: 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函数中标记为注释。在此回调函数中,我想使用Google Map mapRef引用来调用fitBounds API。但是,为了运行此API,我需要使用LatLngBounds创建一个新的new google.map.LatLngBounds()对象。但是如何在父组件中访问google lib?那是我的困惑点

1 个答案:

答案 0 :(得分:1)

尝试使用LatLngBounds创建一个新的new window.google.map.LatLngBounds()对象