Integrating Google Maps with React JS

Asked

Viewed 524 times

1

Personal talk,

I’m having trouble integrating Google maps into React. I saw many people with this doubt, although the documentation of the api is quite complete, most of the examples I saw are within the class model or using some third party library.

Someone who has already had this experience has done it using pure Javascript?

Follow the code of my component:

import React from 'react';


const OverviewMap = () => {

  const script = document.createElement('script');
  script.defer = true;
  script.src = 'https://maps.googleapis.com/maps/api/js?key=CHAVE_AQUI'
  
  document.head.appendChild(script)
  
  const map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 8    
    })  
  
  return (
    <>
      <h1>Olá mundo!</h1>
      <div id='map'>
        {map}
      </div>
    </>
  );

};

export default OverviewMap;

How to make the map instantiated when the page loads? And why do I have this error 'cannot find name google'?

  • noted the example I posted?

  • 1

    @Virgilionovic yes, I just read friend! I managed to render the map after some effort, thank you! : D. I found libraries a little unstable, including maintenance problems. I preferred to use something more generic, although it is more verbose, right?

1 answer

1


That way there are some problems one of them is that the component is not loaded yet and with that the variables also not, do the normal way of the javascript is very problematic, should follow as the ReactJs is designed, finally the correct should follow the following steps or model:

In the file inside the folder public/ the index.html add the reference inside the tag <head>:

<script src="https://maps.googleapis.com/maps/api/js?key=key"></script> 

after this reference now is the time to prepare the component:

import React, { useEffect, useRef } from 'react';

function MapView() {
  const mapRef = useRef();
  useEffect(() => {
    new window.google.maps.Map(mapRef.current, {
      center: { lat: -34.397, lng: 150.644 },
      zoom: 8,
    });
  }, []);
  return <div ref={mapRef} style={{ width: 1000, height: 1000 }}></div>;
}

export default Map;

explained that in the useEffect will be responsible that at the moment after loading the component performs and loads the functions of the instance new window.google.maps.Map, inside that code in your constructor indicate the object to be loaded the map so you have to use the useRef to pass the reference to </div> that will load the map and it must have size (width and height) to display the map.

The way it is in your question I managed to make it work, but there’s a lot of mischief and you have to put a setTimeout to charge at a given time, the problem is if it fails, then the best way is to top or with ready components, example:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.