JustFly1984 / react-google-maps-api

React Google Maps API
MIT License
1.81k stars 437 forks source link

Issue with circle and marker #3258

Open AlexGouget opened 1 year ago

AlexGouget commented 1 year ago

Unusual Issue

I'm experiencing an unusual problem. I need to render a circle, a central marker, and several surrounding markers.

Here's the relevant code:

`export default function FindRelay() {

const [center, setCenter] = useState(centerParis);
const [distance, setDistance] = useState(20);
const [hoveredItem, setHoveredItem] = useState(null);
const [place, setPlace] = useState(null);

//DATA
const [filter, updateFilter] = useReducer(
    (filter, updates) => ({ ...filter, ...updates }),
    { pays: "", cp: "", rayonDeRecherche: center, latitude: "", longitude: "" }
);
const [loading, error, data, hasMore, metadata, progress, fetchData] = useFetch({
    url: `${API_URL}/mondial-relay/get-relay`,
    method: "POST",
    body: filter,
});
useEffect(() => {
    place && fetchData();
}, [filter]);

//GOOGLE MAPS
const { isLoaded, google, loadError } = useJsApiLoader({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
    libraries: libraries,
});
const containerStyle = { width: '50%', height: '90vh' };

//GEOLOCATION
const [userLocation, setUserLocation] = useState({});
navigator.geolocation.getCurrentPosition(position => {
    if (!userLocation.lat && !userLocation.lng) {
        setUserLocation({
            lat: position.coords.latitude,
            lng: position.coords.longitude
        });
    }
});

//AUTOCOMPLETE
const [autocomplete, setAutocomplete] = useState(null);
const onLoad = useCallback((autocomplete) => { setAutocomplete(autocomplete); }, []);
const onPlacesChanged = () => {

    if (autocomplete) {
        setPlace(autocomplete.getPlace());
        let place = autocomplete.getPlace();
        let addressComponents = place.address_components;
        let postalCode, countryIso;

        if (!addressComponents) return

        for (let i = 0; i < addressComponents.length; i++) {
            if (addressComponents[i].types.includes('postal_code')) { postalCode = addressComponents[i].short_name; }
            if (addressComponents[i].types.includes('country')) { countryIso = addressComponents[i].short_name; }
        }

        setCenter({
            lat: autocomplete.getPlace().geometry.location.lat(),
            lng: autocomplete.getPlace().geometry.location.lng()
        });
        updateFilter({
            pays: countryIso,
            cp: postalCode,
            latitude: autocomplete.getPlace().geometry.location.lat(),
            longitude: autocomplete.getPlace().geometry.location.lng(),
        });
    } else { console.log('Autocomplete is not loaded yet!'); }
};

if (!isLoaded || !data) { return <Spin />; }

return (

    <Fragment>
        {isLoaded &&
            // Flex container pour aligner les éléments enfants
            <div className="d-flex flex-row justify-content-center align-items-start mt-3">
                <Form className="bg-transparent" style={{width: "50%"}}>
                    <div className="w-100 d-flex flex-column ">

                        {JSON.stringify(filter)}
                        {JSON.stringify(center)}

                        <Autocomplete
                            onLoad={onLoad}
                            onPlaceChanged={onPlacesChanged}
                            className="Item bg-transparent">
                            <Input placeholder="Ville, Pays etc" />
                        </Autocomplete>

                        <Slider
                            defaultValue={distance}
                            onAfterChange={(e) => {
                                setDistance(e)
                                updateFilter({
                                        rayonDeRecherche: e
                                    })
                            }}
                            tooltip={{ open: true }}/>
                    </div>

                    <div className="overflow-scroll" style={{maxHeight: '80vh'}}>
                        {loading && <Spin/>}
                        <RenderCard data={data} setHoveredItem={setHoveredItem} hoveredItem={hoveredItem} />
                    </div>
                </Form>

                <GoogleMap
                    mapContainerStyle={containerStyle}
                    center={center}
                    zoom={10}>

                    <Circle
                        center={center}
                        radius={distance * 1000}
                        options={{
                            strokeColor: "#ee8a5e",
                            strokeOpacity: 0.8,
                            strokeWeight: 2,
                            fillColor: "#ffa38f",
                            fillOpacity: 0.35,
                        }}
                    />

                    <Marker position={center} />

                    <RenderMarkers
                        data={data}
                        setHoveredItem={setHoveredItem}
                        hoveredItem={hoveredItem}
                        center={center}
                        distance={distance}
                    />
                </GoogleMap>
            </div>
        }
    </Fragment>
)`

In this scenario, I would expect to see a Circle and a Marker on my map. However, nothing appears. The only way I've been able to render the Circle and Marker is by moving them beneath the component, then the watch mode refesh automatically, and the circle appears as expected.

` <GoogleMap mapContainerStyle={containerStyle} center={center} zoom={10}>

                    <RenderMarkers
                        data={data}
                        setHoveredItem={setHoveredItem}
                        hoveredItem={hoveredItem}
                        center={center}
                        distance={distance}
                    />
                    <Circle
                        center={center}
                        radius={distance * 1000}
                        options={{
                            strokeColor: "#ee8a5e",
                            strokeOpacity: 0.8,
                            strokeWeight: 2,
                            fillColor: "#ffa38f",
                            fillOpacity: 0.35,
                        }}
                    />

                    <Marker position={center} />

                </GoogleMap>`

However, when I reload the page, there's nothing displayed on the map. Repeating the same operation makes the circle appear again.

Another odd behavior I noticed is that when I change the radius of the circle using the slider, the original circle remains on the map and a second one is drawn over it.

AlexGouget commented 1 year ago

MAJ: I deploy app on pre-prod server and the issue fly away -_-

luhuanx commented 1 year ago

I have the same problem. Have you solved it on DEV?

AlexGouget commented 1 year ago

Not really, the not occur on prod. I suspect React.StrictMode to be the problem

codellyson commented 9 months ago

Not really, the not occur on prod. I suspect React.StrictMode to be the problem

I can confirm, The issue was no longer there as soon as I turned off strictMode in dev. Thanks for the insight