google-map-react / old-examples

Examples for google-map-react component.
http://google-map-react.github.io/google-map-react/map/main/
357 stars 316 forks source link

Dynamically Set the center of the map #42

Open DevChrisDev opened 4 years ago

DevChrisDev commented 4 years ago

is this able to set the center of the map?

Action: Clicks a button

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

maciejkwas commented 3 years ago

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;