Using Google Map API inside a React component

I am struggling over the way to use Google Map API inside a React component. I did not want to use popular react-google-maps nor google-map-react packages, but rather create my own.

I managed to load the script tag with the Google Map API from the React component. However, how do I manipulate the Google API from here? For example, initializing the map with even basic configuration like below?

  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 8
  });

Here is my component. Any advice is appreciated! thanks!

import React, { Component } from 'react';

// Load Google API in script tag and append 
function loadScript(src) {
  return new Promise((resolve, reject) => {
    let script = document.createElement('script');
    script.src = src;
    script.addEventListener('load', function() {
      resolve();
    });
    script.addEventListener('error', function(e) {
      reject(e);
    });
    document.body.appendChild(script);
  });
}
const script = 'https://maps.googleapis.com/maps/api/js?key=MY_API_KEY';

class MyGoogleMap extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    // first load the script into html
    loadScript(script).then(function() {
      console.log('SUCCESS');
      // Where do I go from here?
    });
  }
  render() {
    return <div />;
  }
}

export default MyGoogleMap;

Answer

I actually found my own solution, so I am sharing for anyone who would meet the same problem.

The basic logic is to use window object to access google. So, after I load the script as I did from the question, I initialize my map as:

  initMap = () => {
    // 'google' could be accessed from 'window' object
    const map = new window.google.maps.Map(
      document.getElementById('googleMap'),
      {
        zoom: 14,
        center: { lat: LATITUDE, lng: LONGTITUDE }
      }
    );
    // putting a marker on it
    const marker = new window.google.maps.Marker({
      position: { lat: LATITUDE, lng: LONGTITUDE },
      map: map
    });
  };

  render() {
    return (
      <div id="googleMap" style={width: WIDTH, height: HEIGHT}/>
    );
  }

Any comment is welcomed 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *