RGM

react google map
GitHub icon

Events

Get instance of google.maps.Map class using ref property or useMap hook. Then subscribe on any event inside useEffect hook using addListener.

Don't forget to unsubscribe in useEffect cleanup.

Sometimes google map fires events like idle in a wrong order, usually wrapping callback into 2 rafs helps.

Don't use code below in production, it's better to intercept bounds changes inside idle event.

// @flow
import * as React from 'react';
import { Map } from 'rgm';
import { useGoogleApiLoader } from '../dev-src/hooks';
import { Ratio, Info } from '../dev-src/controls';
// https://developers.google.com/maps/documentation/javascript/reference/map#MapOptions
const MAP_OPTIONS = {
zoom: 9,
center: {
lat: 59.936,
lng: 30.314,
},
};
export default function Events() {
const api = useGoogleApiLoader();
const [bounds, setBounds] = React.useState(null);
const [map, setMap] = React.useState(null);
React.useEffect(() => {
if (map != null) {
const boundsChangedListener = map.addListener('bounds_changed', () => {
const bounds = map.getBounds();
setBounds(bounds);
});
return () => {
boundsChangedListener.remove();
};
}
}, [map]);
return (
<div>
<Info>{bounds?.getCenter().toString() ?? ' '}</Info>
<Ratio value={3 / 4}>
{api && <Map ref={setMap} api={api} options={MAP_OPTIONS} />}
</Ratio>
</div>
);
}
EXAMPLES ARE PROVIDED UNDER THE BEER-WARE LICENSE