Home > Mobile >  how can i use Google maps with primereact
how can i use Google maps with primereact

Time:06-11

I am trying to use the GMap component that is part of the primereact library, but i keep getting this error :

Unhandled Runtime Error ReferenceError: google is not defined

I am working on a next.js app, here is the simple code i copied/pasted from primerreact library:

import { GMap } from 'primereact/gmap';

const DealershipLocation = () => {

  const options = {
    center: {lat: 36.890257, lng: 30.707417},
    zoom: 12
};
  return (
    <div>
      <GMap options={options} style={{width: '100%', minHeight: '320px'}} />
    </div>
  )
}

export default DealershipLocation

CodePudding user response:

From the GMAP showcase it looks like you aren't loading Google Maps JS correctly.

Add these functions... where key=XXX is your Google Maps key

const loadGoogleMaps = (callback) => {
    const existingScript = document.getElementById('googleMaps');

    if (!existingScript) {
        const script = document.createElement('script');
        script.src = 'https://maps.google.com/maps/api/js?key=XXX';
        script.id = 'googleMaps';
        script.async = true;
        script.defer = true;
        document.body.appendChild(script);

        script.onload = () => {
            if (callback) callback();
        };
    }

    if (existingScript && callback) callback();
};

const removeGoogleMaps = () => {
    const mapScript = document.getElementById('googleMaps');

    if (mapScript) {
        mapScript.parentNode.removeChild(mapScript);

        const head = document.getElementsByTagName('head')[0];
        const scripts = head.getElementsByTagName('script');
        for (let i = 0; i < scripts.length; i  ) {
            let script = scripts[i];
            let src = script.src;

            if (src.startsWith('https://maps.google.com/maps')) {
                head.removeChild(script);
            }
        }
    }
};

Then load it in a React Hook..

const [googleMapsReady, setGoogleMapsReady] = useState(false);

    useEffect(() => {
        loadGoogleMaps(() => {
            setGoogleMapsReady(true);
        });

        return () => {
            removeGoogleMaps();
        }
    }, []);
  • Related