Zooming to stockist area in Google Maps after clicking on stores

36 Views Asked by At

I am using @react-google-maps/api. I want to zoom in on the map until I can see the names of the clicked stores (selectedStore) in the map. I also want the transitions to be smoother instead of flashing the new geographic location.

Here's my code:

const CENTER = {lng: -x.xxxxxx, lat: xx.xxxxxx, _type: 'geopoint'};

const Map: React.FC<MapProps> = ({
  locations,
  selectedStore,
  setSelectedRegion,
  ...options
}) => {
  const centerLocation = CENTER ?? locations[0]?.geo;
  const {isLoaded} = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: PUBLIC_GMAPS_API!,
  });

  const [map, setMap] = useState<google.maps.Map>();
  const [panQueue, setPanQueue] = useState();

  const onLoad = useCallback(
    function callback(map: any) {
      map.setOptions({
        center: centerLocation,
        zoom: 3,
      });
      setMap(map);
    },
    [centerLocation],
  );

  const onIdle = useCallback(
    function callback() {
      if (panQueue) {
        map.panTo(panQueue);
        map.setZoom(6);
        setPanQueue(undefined);
      }
    },
    [map, panQueue],
  );
  const onUnmount = useCallback(function callback(map: any) {
    setMap(null);
  }, []);

  const smoothlyAnimatePanTo = (geo) => {
    if (!map) return;
    map.setZoom(6);
    setPanQueue(geo);
  };

  useEffect(() => {
    if (!map) return;
    if (!selectedStore) {
      map.setOptions({
        zoom: 6,
      });
    } else {
      smoothlyAnimatePanTo(selectedStore?.geoLocation);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedStore]);

  useEffect(() => {
    if (map && selectedStore?.geoLocation) {
      map.panTo(selectedStore.geoLocation);
      map.setZoom(6);
    }
  }, [map, selectedStore]);

  return isLoaded ? (
    <GoogleMap
      mapContainerClassName="h-full w-full"
      onLoad={onLoad}
      onIdle={onIdle}
      onUnmount={onUnmount}
      options={{
        styles: mapStyles,
        streetViewControl: false,
        mapTypeControl: false,
        fullscreenControl: false,
        zoomControl: false,
        minZoom: 4,
        maxZoom: 12,
        restriction: {
          latLngBounds: {
            north: 85.0,
            south: -85.0,
            west: -180.0,
            east: 180.0,
          },
          strictBounds: true,
        },
      }}
    >
      {locations.map((location) => {
        return (
         <Marker ... />
        );
      })}
    </GoogleMap>
  ) : (
    <></>
  );
};

How can I achieve a smoother transition and zooming in?

0

There are 0 best solutions below