old-examples icon indicating copy to clipboard operation
old-examples copied to clipboard

Dynamically Set the center of the map

Open DevChrisDev opened this issue 4 years ago • 1 comments

is this able to set the center of the map?

Action: Clicks a button

Expected output: Center the map, on e.g Egypt.

DevChrisDev avatar Mar 21 '20 05:03 DevChrisDev

Year have passed, but i'm gonna answer anyway. Just set map reference on init, and then refer to it and use just native google maps api according to their docs, here's simplified example:

import { useEffect, useRef } from 'preact/hooks';
import GoogleMapReact from 'google-map-react';

const CustomMap = () => {
  const mapRef = useRef(null);

  useEffect(() => {
    mapRef.current &&
      mapRef.current.setCenter({ lat: 10, lng: 20 });
  }, []);

  return (
    <div>
      <GoogleMapReact
        yesIWantToUseGoogleMapApiInternals
        onGoogleApiLoaded={({ map }) => {
          mapRef.current = map;
        }}
      >
      </GoogleMapReact>
    </div>
  );
};

export default CustomMap;

maciejkwas avatar Feb 21 '21 15:02 maciejkwas