javascriptreactjsreact-google-mapsreact-google-maps-api

React-google-maps not displaying props


I am trying to display a simple Circle on the map using the Circle prop. It works perfectly fine on one computer using chrome however it will not display on the map when on another computer using the same browser.

The circle only displays after I manually force a rerender - example by creating a second circle my page refreshes and shows the intended circle on the map.

However once i refresh the browser window the circle disapears.

I have tried adding a Zindex without any luck, I have also tried using the newer useJsApiLoader rather than but am experiencing the same issue.

import React, { useRef } from 'react';
import { GoogleMap, LoadScript, StandaloneSearchBox, Circle } from '@react-google-maps/api';

const EndpointMap = () => {

  const searchBoxRefLocation = useRef(null);
  const mapRef = useRef(null); // Reference to Google Map component
  const apiKey = 'myKey';

  return (
    <LoadScript googleMapsApiKey={apiKey} libraries={['places']}>
      <div style={{ height: '100vh', width: '100vw' }}>
        <GoogleMap
          ref={mapRef}
          mapContainerStyle={{ height: '100vh', width: '100vw' }}
          center={{ lat: 49.3, lng: -123.2194 }}
          zoom={8}
        >
        <Circle
        center={{ lat: 49.2, lng: -123.2194 }}
        radius={10000}
        options={{
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.1,
        }}
        />
        </GoogleMap>
      </div>
    </LoadScript>
  );
};
export default EndpointMap;

Solution

  • How about invoking it as a side effect using useEffect?

    Have the circle loaded once the map is rendered.

    const [shouldRenderCircle, setShouldRenderCircle] = useState(false);
    
    useEffect(() => {
        const delayRender = setTimeout(() => {
            setShouldRenderCircle(true);
        }, 500); // Adjust the delay as needed
    
        return () => clearTimeout(delayRender);
    }, []);
    
    {shouldRenderCircle && (
            <Circle
              center={{ lat: 49.2, lng: -123.2194 }}
              radius={10000}
              options={{
                strokeColor: '#FF0000',
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#FF0000',
                fillOpacity: 0.1,
              }}
            />
     )}