The <Map> component allows you to manage camera parameters (center, zoom, heading, and tilt) using either controlled or uncontrolled patterns.
Uncontrolled Mode
Use defaultCenter and defaultZoom to set the initial state. These values are only applied during the map's first initialization. Subsequent user interactions will change the map state without needing to update props.
const UncontrolledMap = () => {
return <Map defaultCenter={{lat: 40.7, lng: -74}} defaultZoom={12}></Map>;
};
Controlled Mode
Use center and zoom to keep the map synchronized with your application state. When a user interacts with the map, the onCameraChanged event is fired, providing the new camera parameters via ev.detail. You must then update your state to reflect these changes.
import {MapCameraChangedEvent, MapCameraProps} from '@vis.gl/react-google-maps';
const INITIAL_CAMERA = {
center: {lat: 40.7, lng: -74},
zoom: 12
};
const ControlledMap = () => {
const [cameraProps, setCameraProps] =
useState<MapCameraProps>(INITIAL_CAMERA);
const handleCameraChange = useCallback((ev: MapCameraChangedEvent) =>
setCameraProps(ev.detail)
);
return <Map {...cameraProps} onCameraChanged={handleCameraChange}></Map>;
};
Externally Controlled Mode
By setting the controlled prop to true, the map disables all user control inputs and will only render what is explicitly specified in the camera props.