@react-google-maps/api shows loading... when the network is slow or chrome version is too low

119 views Asked by At

I have a website for rendering maps from the @react-google-maps/api library. Everything works fine but when I make the network so slow or if your chrome version is too low like around 80.xxxx it shows Loading... and the map component stucks at there like this Loading...

And my code is this

import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { GoogleMap, InfoBox, LoadScript, Marker, useJsApiLoader } from '@react-google-maps/api';
import InfoBoxComponent from '@react-google-maps/api/dist/components/addons/InfoBox';
// other imports
export interface InsMapProps {
    markers: Mkr[];
}

const InsMap = ({ markers }: InsMapProps) => {
    const infoBoxRef = useRef<InfoBoxComponent>(null);
    const { markerId } = useMarker();
    const [isInfoBoxOpen, setIsInfoBoxOpen] = useState<boolean>(false);
    const [responseMarkers, setResponseMArkers] = useState<Mkr[]>([]);
    const [selectedMarker, setSelectedMarker] = useState<Mkr | null>(null);
    const [map, setMap] = useState<google.maps.Map<Element>>();
    const [zoom] = useState(14);
    const mapRef = useRef<google.maps.Map<Element>>();
    const { city, district, insType, country, searchStr } = useInsStore();
    const { ins } = useInsList();
    const [center, setcenter] = useState<TStartPoint>({
        lat: 0,
        lng: 0
    });

    const apiKey = getGmapsKeys();

    const { isLoaded } = useJsApiLoader({
        googleMapsApiKey: apiKey
    });

    const version = getBrowser();

    const onLoadMap = useCallback(
        (mapFromLib: google.maps.Map<Element>) => {
            mapRef.current = mapFromLib;
            setMap(mapFromLib);
        },
        [map]
    );
    const convertToNumber = (point: TStartPoint): TStartPoint => {
        const n: TStartPoint = {
            lat: parseFloat(String(point.lat)),
            lng: parseFloat(String(point.lng))
        };
        return n;
    };
    const onMarkerClick = useCallback(
        (event) => {
            setSelectedMarker(event);
            setIsInfoBoxOpen(true);
            console.log('selected marker=>', event);
        },
        [map]
    );
    const markerType = (obj: any) => {
        switch (obj.typeId) {
            case '1001':
                return Hastane;
            case '1002':
                return Eczane;
            case '1008':
                return Doktor;
            default:
                return Pin;
        }
    };
    const optionType = (obj: any, index: any) => {
        const result = {
            ...obj,
            id: obj.id,
            index
        };
        return result;
    };
    const setMarkersFunction = (insListArr: TInstitution[]) => {
        const tempMarkers: Array<Mkr> = [];

        insListArr.forEach((marker, index: any) => {
            if (marker.name.toLocaleLowerCase('tr').includes(searchStr)) {
                const _marker: Mkr = {
                    position: {
                        lng: Number(marker['lng']),
                        lat: Number(marker['lat'])
                    },
                    icon: markerType(marker),
                    zIndex: marker.selected ? 999 : 100,
                    options: optionType(marker, index)
                };
                tempMarkers.push(_marker);
            }
        });
        return tempMarkers;
    };
    const filterAll = async () => {
        const newOnes = setMarkersFunction(ins);
        setResponseMArkers([...newOnes]);
    };
    useLayoutEffect(() => {
        filterAll();
    }, [district, insType, markers.length, ins, searchStr]);
    useEffect(() => {
        const canPan = selectedMarker !== null && mapRef.current;
        if (canPan) {
            mapRef.current?.panTo(selectedMarker.position);
        }
    }, [selectedMarker]);
    useEffect(() => {
        if (markerId.length > 0) {
            responseMarkers.forEach((mark: Mkr) => {
                if (mark.options.id && mark.options.id === markerId) {
                    onMarkerClick(mark);
                } else {
                    return null;
                }
            });
        }
    }, [markerId]);
    useEffect(() => {
        const canSetCenter = city !== null;
        if (canSetCenter) {
            mapRef.current?.setZoom(12);
            console.log('center', center);
            setcenter({
                lat: Number(city.coorY),
                lng: Number(city.coorX)
            });
        }
    }, [city, district, country]);

    useEffect(() => {
        console.log({ district });
        const canSetCenter = district !== null && district.code !== '9999';
        if (canSetCenter) {
            mapRef.current?.setZoom(14);
            setcenter({
                lat: Number(district?.coorY),
                lng: Number(district?.coorX)
            });
        }
    }, [district]);

    return (
        <div className="InsMap" data-testid="InsMap" id="InsMap">
            {isLoaded ? (
                <LoadScript
                    onError={(e) => console.log('loadscript error', e)}
                    googleMapsApiKey={getGmapsKeys()}
                    language={'tr-TR'}
                >
                    <GoogleMap
                        mapContainerStyle={mapContainerStyle}
                        zoom={zoom}
                        options={mapOptions}
                        onLoad={onLoadMap}
                        center={convertToNumber({ lat: center.lat, lng: center.lng })}
                        onCenterChanged={() => mapRef.current?.getCenter().toJSON()}
                    >
                        <MapNav></MapNav>
                        {responseMarkers.map((marker) => {
                            return (
                                <Marker
                                    position={marker.position}
                                    key={marker.options.index}
                                    icon={marker.icon}
                                    zIndex={marker.zIndex}
                                    onClick={() => onMarkerClick(marker)}
                                ></Marker>
                            );
                        })}
                        {isInfoBoxOpen &&
                            selectedMarker &&
                            selectedMarker?.options?.type !== 'target' && (
                                <InfoBox
                                    options={{
                                        zIndex: 600,
                                        pixelOffset: new window.google.maps.Size(-100, 0)
                                    }}
                                    ref={infoBoxRef}
                                    onCloseClick={() => setIsInfoBoxOpen(!isInfoBoxOpen)}
                                    position={selectedMarker.position}
                                    zIndex={700}
                                >
                                    <InsInfoCard selectedMarker={selectedMarker}></InsInfoCard>
                                </InfoBox>
                            )}
                    </GoogleMap>
                </LoadScript>
            ) : (
                <h4 className="text-center m-12">
                    Tarayıcı versiyonunuz {version} güncel değildir.<br></br> Bu versiyon harita
                    görünümünü desteklememektedir.<br></br> Lüfen tarayıcınızı güncel bir versiyona
                    yükseltiniz.
                </h4>
            )}
        </div>
    );
};

export default InsMap;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Is there any way I can get rid of this loading... text and I can show text like in here ==>

                <h4 className="text-center m-12">
                    Tarayıcı versiyonunuz {version} güncel değildir.<br></br> Bu versiyon harita
                    görünümünü desteklememektedir.<br></br> Lüfen tarayıcınızı güncel bir versiyona
                    yükseltiniz.
                </h4>

0

There are 0 answers