react-google-maps:如何使用 fitBounds、panBy、panTo、panToBounds public API?

react-google-maps: how to use fitBounds, panBy, panTo, panToBounds public APIs?

根据React Google Maps library,你可以从ref对象中调用这四个方法。

奇怪的是,这些方法应该接收两个参数,一个地图实例和其他参数,如下所示:

fitBounds(map, args) { return map.fitBounds(...args); }

但是,当以这种方式调用 fitBounds() 时,地图上没有任何反应,没有更改边界,也没有抛出任何错误。这是我构建组件的方式,在 componentDidUpdate:

中调用 fitBounds
import React from 'react'
import { withGoogleMap, GoogleMap, InfoWindow, Marker, OverlayView } from 'react-google-maps'
import InfoBox from 'react-google-maps/lib/addons/InfoBox'
import map from 'lodash/map'

// Higher-Order Component
const AllocatedPlacesMap = withGoogleMap(props => (
  <GoogleMap
    center={props.center}
    defaultZoom={4}
    options={{ scrollwheel: false, minZoom: 3, maxZoom: 15 }}
    onCenterChanged={props.onCenterChanged}
    ref={props.onMapMounted}>
    {props.markers.map((marker, index) => (
      <Marker
        key={index}
        position={marker.position}
      />
    ))}
  </GoogleMap>
));

class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  getCenter = () => {
    this._bounds = new google.maps.LatLngBounds();

    this.props.markers.forEach((marker, index) => {
      const position = new google.maps.LatLng(marker.lat, marker.lng);
      this._bounds.extend(position);
    });

    return this._bounds.getCenter();
  }

  componentDidUpdate() {
    this._map.fitBounds(this._map, this._bounds);
  }

  handleMapMounted = (map) => {
    this._map = map;
  }

  render() {
    return (
      <div className="allocated-places">
        <AllocatedPlacesMap
          containerElement={
            <div style={{ height: `100%` }} />
          }
          mapElement={
            <div style={{ height: `100%` }} />
          }
          center={this.getCenter()}
          markers={props.markers}
          onMapMounted={this.handleMapMounted}
        />
      </div>
    )
  }
}

export default Map;

知道在这种情况下调用 fitBounds() 的正确方法是什么吗?在这方面似乎缺乏文档和示例。

查看函数定义 fitBounds(map, args) { return map.fitBounds(...args); } 我们可以看到 spread operator 应用于 args。这表明 args 应该是一个数组。

因此,在您的代码中,第二个参数应该是数组类型:

this._map.fitBounds(this._map, [this._bounds]);

您还可以包含数组的第二个元素,该元素将被转换为地图 JavaScript API fitBound() 方法的第二个可选参数 padding

this._map.fitBounds(this._map, [this._bounds, 100]);

希望对您有所帮助!

这就是你如何使用 react map ref 调用 panTo 和 fitBounds

this.map.panTo({
  lat:e.latLng.lat(), lng: e.latLng.lng()
})
const bounds = new google.maps.LatLngBounds()
bounds.extend({
  lat:e.latLng.lat(), lng: e.latLng.lng()
})
this.map.fitBounds(bounds)