react-google-maps fitBounds 和 panToBounds 不缩放地图

react-google-maps fitBounds and panToBounds does not scale the map

const Map = withGoogleMap(props => {
  const { activeMarker, zoom, center, showInfoWindow, products } = props;
  const [selectedPlace, setSelectedPlace] = useState(null);

  // Iterate items to size, center, and zoom map to contain all markers
  const fitB = () => {
    let bounds = new window.google.maps.LatLngBounds();
    console.log({ bounds });
    products &&
      products.map(place => {
        bounds.extend({
          lat: parseFloat(place.latitude),
          lng: parseFloat(place.longitude)
        });
      });

    console.log({ extended: bounds });

    return bounds;
  };

  return (
    <GoogleMap
      defaultOptions={{
        styles: MapTheme,
        zoomControl: true,
        zoomControlOptions: {
          position: google.maps.ControlPosition.LEFT_TOP
        },
        mapTypeControl: false,
        scaleControl: true,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: true
      }}
      panToBounds={{ latLngBounds: () => fitB() }}
      fitBounds={{ latLngBounds: () => fitB() }}
      zoom={zoom}
      center={center}
    >
      {products.map(bc => (
        <Marker
          key={bc.id}
          position={{
            lat: parseFloat(bc.latitude),
            lng: parseFloat(bc.longitude)
          }}
          icon={{
            url: bc.id == activeMarker ? BC_MARKER_ACTIVE : BC_MARKER,
            scaledSize: new window.google.maps.Size(20, 20)
          }}
        />
      ))}
    </GoogleMap>
  );
});

我正在为地图使用 react-google-maps,而 fitBounds/panToBounds 的默认道具似乎根本没有设置地图的边界。

至于代码。 fitBounds/panToBounds props 似乎根本没有调用 fitB() 方法。

我想使用 Google Map

的 fitBounds 方法调整地图大小以放大并适应标记

它不起作用,因为 fitBounds() 是一种方法,而不是 GoogleMap 的 属性。同样 panToBounds()。您需要将边界设置为您的地图参考。

例如:

const refs = {}

onMapMounted: ref => {
  refs.map = ref;
}

那么你可以这样做:

let bounds = new window.google.maps.LatLngBounds();
bounds.extend({
  lat: parseFloat(place.latitude),
  lng: parseFloat(place.longitude)
});
refs.map.fitBounds(bounds);

使用图书馆的文档作为指导:https://tomchentw.github.io/react-google-maps/

希望对您有所帮助!