How to implement Google Maps JS API in React without an external library?

Asked
Active3 hr before
Viewed126 times

5 Answers

withoutexternallibraryimplementgooglereact
90%

The issue has to do with how async and defer works when using the google maps API.,Basically the google API is not loaded yet when your code reaches the point when the map has to be rendered. Please take a look at this post to understand how that works:,My question is this: how do I use the following snippet from the Google documentation for the API within React? ,Even if it's not the preferred or most elegant way to do it, some basic understanding on how to implement the API without any external library would be greatly appreciated. Thank you!

SOLUTION ONE Don't use async and defer in your script tag in order to allow the script to be downloaded before executing your app:

<script src='https://maps.googleapis.com/maps/api/js?key=AIzaSyDZfVO29Iytspv4xz7S68doIoiztiRLhbk&callback=initMap'>
</script>

SOLUTION TWO Create some sort of recursive checker in order to see if the google api has loaded in order to continue your app's execution once the google maps api is availabe:

class MyMap extends Component{

  constructor(props){
    super(props);
    this.googleChecker = this.googleChecker.bind(this);
    this.renderMap = this.renderMap.bind(this);
  }

  googleChecker() {
    // check for maps in case you're using other google api
    if(!window.google.maps) {
      setTimeout(googleChecker, 100);
      console.log("not there yet");
    } else {
      console.log("we're good to go!!");
      // the google maps api is ready to use, render the map
      this.renderMap();
    }
  }

  renderMap(){
    const coords = { lat: 41.375885, lng: 2.177813 };
    // create map instance
    new google.maps.Map(this.refs.mapContainer, {
      zoom: 16,
      center: {
        lat: coords.lat,
        lng: coords.lng
      }
    });
  }

  componentDidMount(){
    this.googleChecker();
  }

  render(){
    return(
      <div className="card map-holder">
        <div className="card-block" ref="mapContainer" />
      </div>
    );
  }
}
load more v
88%

Step 1: Assuming you have a React application already set up using create-react-app, you’ll first need to register an API from the Google Developers dashboard and enable the Maps JavaScript API. Details on how to do this can be found here.,The approach outlined in this post makes it super easy to use Google Maps in your React apps with zero dependencies. This means you have full access to the Google Maps JavaScript API with no abstractions.,Provided you have set your API key, this will render the map. If the GoogleMap is used multiple times within the same application you will need to ensure that the id prop passed in to the component is unique.,Step 2: Create a custom GoogleMap component with the following implementation:

// Map.tsx

import React, { Component } from 'react';
import { render } from 'react-dom';

class Map extends Component {
    constructor(props) {
        super(props);
        this.onScriptLoad = this.onScriptLoad.bind(this)
    }
    
    onScriptLoad() {
        const mapId = document.getElementById(this.props.id);
        const map = new window.google.maps.Map(mapId, this.props.options);
    }
    
    componentDidMount() {

        if (window.google) {
            this.onScriptLoad();
            return;
        }
        
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = `https://maps.google.com/maps/api/js?key=YOUR_API_KEY`;
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);
        
        s.addEventListener('load', e => {
            this.onScriptLoad()
        })
    }
    
    render() {
        return (
            <div style={{ width: 100%, height: 100% }} id={this.props.id} />
        );
    }
}

export default GoogleMap
load more v
72%

Then, we have to define some important constants that our GoogleMap module requires:,The final step is to use the DirectionsRenderer module from react-google-maps - we need to map it and pass as children to GoogleMap:,In the line above, we get an object from origins according to the selected ID and based on that data, we can now display the InfoWindow component that is also passed as children to the GoogleMap:,Let's import our constants into the MapContainer.js and comment the ones that will be used a bit later:

.css - 10 a0b6s {
      color: var (--chakra - colors - white);background - color: #011627;font-size:80%;line-height:1.7;background:var(--chakra-colors-sudo-violet);padding:var(--chakra-space-6);display:block;overflow-x:auto;}export const MOCK_DESTINATIONS_DATA =[{
         id: 1,
         title: 'Falun',
         coordinates: {
            lat: 60.610361157011646,
            lon: 15.63610136902125
         },
         src: 'https://i.pinimg.com/originals/09/9e/60/099e600bcfa057bf1c9ecdcce0ad529c.jpg',
      }, ]
      export const MOCK_ORIGINS_DATA = [{
         id: 2,
         title: 'Uppsala',
         coordinates: {
            lat: 59.86700302991904,
            lon: 17.639901897585162
         },
         src: 'https://d3aux7tjp119y2.cloudfront.net/images/oscar-ekholm-DC50Oj2m4CY-unsplash-CMSTemplate.width-1650_5AWSVQc.jpg',
      }, ]
load more v
65%

In this article, we’ll look at how we to connect the Google API and build a Google Maps Component.,Handling access to the Google API within our components.,This article is not only about how to use Google Maps, but how to use 3rd party libraries in React generally and how to build up rich interactive components.,The React Way is to write our Marker components as children of the Map component.

  • ScriptCache.js - The backbone of this method which asynchronously loads JavaScript <script> tags on a page. It will only load a single <script> tag on a page per-script tag declaration. If it's already loaded on a page, it calls the callback from the onLoad event immediately.
this.scriptCache = cache({
   google: 'https://api.google.com/some/script.js'
});
load more v
75%

This project aims to provide a performance-first React-centric extendable map engine.,There was a problem preparing your codespace, please try again.,Enable/disable touch and mouse events as needed - you could make a 100% static server rendered react map, ReactJS Maps without external dependencies

Bumps [ws](https://github.com/websockets/ws) from 6.2.1 to 6.2.2.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/commits)

---
updated-dependencies:
- dependency-name: ws
dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

   Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

Other "without-external" queries related to "How to implement Google Maps JS API in React without an external library?"