Search code examples
javascriptreactjsgoogle-maps-api-3react-google-maps

onCenterChange callback returns undefined @react-google-maps/api


I have been using a library called @react-google-maps/api and I want to store the map center as react state and I want the user to be able to drag the map while the marker always stays at the center of the map (uber style location selection)

The Problem is when I call the onCenterChange of the component, it returns me undefined

and when after store the map instance (recieved on the onLoad callback) as react state. The map instance returns the exact same center everytime (I guess the state save is static)

<GoogleMap
        id={id}
        zoom={zoom}
        center={center}
        options={options}
        mapContainerStyle={{ width, height }}
        onLoad={m => {
          if (!map) setMap(m);
        }}
        onCenterChanged={e => {
          console.log(map);
          if (map) {
            console.log(parseCoords(map.getCenter()));
          }
        }}
      >
        {children}
      </GoogleMap>

Solution

  • Indeed, onCenterChanged event does not accept any arguments in @react-google-maps/api:

    onCenterChanged?: () => void;
    

    Instead map instance could be retrieved via onLoad event handler and map center saved in state like this:

    function Map(props) {
      const mapRef = useRef(null);
      const [position, setPosition] = useState({
        lat: -25.0270548,
        lng: 115.1824598
      });
    
      function handleLoad(map) {
        mapRef.current = map;
      }
    
      function handleCenterChanged() {
        if (!mapRef.current) return;
        const newPos = mapRef.current.getCenter().toJSON();
        setPosition(newPos);
      }
    
      return (
        <GoogleMap
          onLoad={handleLoad}
          onCenterChanged={handleCenterChanged}
          zoom={props.zoom}
          center={props.center}
          id="map"
        >
        </GoogleMap>
      );
    }
    

    Here is a demo which demonstrates how to keep the marker centered of the map while dragging the map.