Pete Fowler
blog.petefowler.dev

blog.petefowler.dev

How to add Google maps and markers to a React site

Photo by NisonCo PR and SEO on Unsplash

How to add Google maps and markers to a React site

Pete Fowler's photo
Pete Fowler
·Nov 12, 2022·

2 min read

To get started with Google maps, don't use the official Google documentation and NPM package. It's more difficult to use and the documentation is not great. The 3rd party google map react NPM package has 281,893 weekly downloads, whereas the NPM package referenced in the official Google documentation, @googlemaps/react-wrapper, has only 107,832 weekly downloads.

Install NPM package

First, install the NPM package with npm i google-map-react.

Create a map component

There is code on the NPM google map react page to get started building a map component.

  • Import the NPM package at the top of the map component withimport GoogleMapReact from 'google-map-react';
  • Build a standard component with props of zoom and center
  • Add a prop for markers if desired
  • Use the component and pass in the props
import GoogleMapReact from 'google-map-react';
import style from './Map.module.css';

export default function Map({center, zoom, markers}){

  return (
    <div className={style.map}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: process.env.REACT_APP_API as string }}
        defaultCenter={center}
        defaultZoom={zoom}
      >
        {markers}
      </GoogleMapReact>
    </div>
  );
}

The bootstrapURLKeys prop requires an API key. In the above example it is stored in an environment variable. Go to the Google cloud console to get one. It must be used in the front end here and would be insecure in the browser, but the Google cloud console allows you to restrict the API key to certain sites or IP addresses.

Markers component

Above, I am passing the variable markers as a prop to the map component. The markers variable is an array of marker components. They could be any React component. They need the props lat and lng in order to be placed on the map at the desired location. Below is an example of creating some markers from data fetched from a back end. The markers later get passed to the map component.

useEffect(() => {
    fetch(`/locations`)
    .then(r => {
      if(r.ok) {
        r.json().then(data => setMarkers(data.map(loc => 
          <Marker key={loc.id} 
            id={loc.id} 
            name={loc.name} 
            lat={loc.coordinates.split(',')[0]} 
            lng={loc.coordinates.split(',')[1]}
              // lat and lng are just numbers for latitude and longitude
          />
        )));
      } else {
        r.json().then(err => console.log(err));
      }
    })
  }, [])

The markers are passed to the map component when it is called like this:

<Map center={{lat: 39.725194, lng: -105.175531}} zoom={7} markers={markers}/>

The center prop is an object with lat and lng keys, and zoom is an integer. The map component must have a defined height and width, otherwise it will not appear. In this example, it is the <div> containing the <GoogleMapReact> component that has a set height and width.

What it looks like

map.jpg

The markers can be customized to be anything, have modal windows appear when hovered, etc.

 
Share this