google-map-react icon indicating copy to clipboard operation
google-map-react copied to clipboard

Cannot use react context for maps custom control

Open cnkyrpsgl opened this issue 4 years ago • 2 comments

Google maps api suggests creating custom control by creating div element. In this way, div element is created out of react dom tree so redux is not applicable to use. I made react wrapper element for this div element that rerenders it according to redux context. It is a burnout to wrap complex components. I tried even refs but not worked. It will be useful to add any feature or help to make react custom control elements easier. Thanks!

cnkyrpsgl avatar Oct 11 '21 11:10 cnkyrpsgl

This appears to work for me:

const TestControl = () => {
  const map = useGoogleMap();
  const [controlIndex, setControlIndex] = useState<number>();
  const [firstRender, setFirstRender] = useState(true);
  const [position] = useState(window.google.maps.ControlPosition.TOP_LEFT);
  
  useEffect(() => {
    return () => {
      if (controlIndex !== undefined) map?.controls[position].removeAt(controlIndex);
    };
  }, [controlIndex,
    map,
    position]);

  return (<div ref={el => {
    if (!firstRender) return;
    setFirstRender(false);
    setControlIndex(map?.controls[position].push(el));
  }} style={{ backgroundColor: 'red' }}>
    Test
  </div>);
};

TaylorDale avatar Nov 08 '21 04:11 TaylorDale

That is my problemn too. Where do i get 'useGoogleMap()' from?

penguinuux avatar May 03 '23 21:05 penguinuux