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

I am using react-google-maps for maps and the default props for 's fitBounds/panToBounds does not seem to set the bounds to the map at all.

As for the code. fitBounds/panToBounds props does not seem to call fitB() method at all.

I want to resize the map to zoom-in and fit in with the markers using the fitBounds method of Google Map

ash1f
  • 89
  • 2
  • 8

1 Answers1

2

It's not working because fitBounds() is a method, not a property of GoogleMap. Likewise with panToBounds(). You need to set the bounds to your map reference.

E.g.:

const refs = {}

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

Then you can do:

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

Use the library's documentation for guidance: https://tomchentw.github.io/react-google-maps/

Hope this helps!

evan
  • 5,443
  • 2
  • 11
  • 20