React google map integration with Live Demo

Today we will learn how to integrate google map in your React Application. In this React google map integration tutorial, we would love to share each things step by step with example.

Before start integrating Google Map in your React Application, We need a React Project. If you don’t know how to create a new project. Follow this tutorial.

So, Let’s get started React google map integration

First, let’s add a placeholder for Google Map

Open App.js file and replace the render method with below html markup

render() {
    return (
    <div className="row mt-5">
        <div className="col-md-10 mx-auto">
            <h2 className="text-left">Google Map</h2>
            <div className="card mt-3">
                <div className="card-body">
                    <div ref="map" style={{'width':'100%', 'height':'400px' }}></div>
                </div>
            </div>
        </div>
    </div>
    );
}

Here, You might be notice that ref="map" attribute. The Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

Next, Loading the Maps JavaScript API

Now, I am going to load the Maps JavaScript API in the App.js file. If you don’t want to load it globally. You can create a new component and load it.

So, open the App.js file and put the below two methods on this

renderMap = () => {

    window['initMap'] = () => {
        this.loadMap();      
    }
    if(!window.document.getElementById('google-map-script')) {
        var s = window.document.createElement("script");
        s.id = "google-map-script";
        s.type = "text/javascript";
        s.src = "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;callback=initMap";
        
        window.document.body.appendChild(s);
    } else {
        this.loadMap();
    }
}
loadMap = () => {

    var map = new window['google'].maps.Map(this.refs.map, {
        center: {lat: 22.7196, lng: 75.8577},
        zoom: 8
    });
    
    var marker = new window['google'].maps.Marker({
        position: {lat: 22.7196, lng: 75.8577},
        map: map,
        title: 'Hello World!',
        draggable: true,
        animation: window['google'].maps.Animation.DROP,
    });

    var contentString = '<div id="content">'+
    '<div id="siteNotice">'+
    '</div>'+
    '<h3 id="thirdHeading" class="thirdHeading">W3path.com</h3>'+
    '<div id="bodyContent">'+
    '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>'+
    '</div>'+
    '</div>';

    var infowindow = new window['google'].maps.InfoWindow({
        content: contentString
    });

    marker.addListener('click', function() {
        infowindow.open(map, marker);
    });
    
}    

In order to do any kind of interaction with the Maps API, you need an API key from Google. Follow the instructions here to get that set up. After the setup complete, You need to replace YOUR_API_KEY with google map key.

You may noticed that, we have load the Google Maps JavaScript CDN under the renderMap method.

The renderMap method will check that the Google Maps JavaScript CDN is already loaded or not. If not then it will load the Google Maps JavaScript CDN. If already loaded then will call the loadMap method.

The loadMap will draw the map.

Next, We will call the renderMap method under componentDidMount method. like this

componentDidMount() {
    this.renderMap();
}

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree).

After above changes our App.js file will looks like this

import React, { Component } from 'react';

class App extends Component {

    componentDidMount() {
        this.renderMap();
    }

    renderMap = () => {
  
        window['initMap'] = () => {
          this.loadMap();      
        }
        if(!window.document.getElementById('google-map-script')) {
          var s = window.document.createElement("script");
          s.id = "google-map-script";
          s.type = "text/javascript";
          s.src = "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;callback=initMap";
          
          window.document.body.appendChild(s);
        } else {
          this.loadMap();
        }
    }

    loadMap = () => {

        var map = new window['google'].maps.Map(this.refs.map, {
            center: {lat: 22.7196, lng: 75.8577},
            zoom: 8
        });
        
        var marker = new window['google'].maps.Marker({
            position: {lat: 22.7196, lng: 75.8577},
            map: map,
            title: 'Hello World!',
            draggable: true,
            animation: window['google'].maps.Animation.DROP,
        });
    
        var contentString = '<div id="content">'+
        '<div id="siteNotice">'+
        '</div>'+
        '<h3 id="thirdHeading" class="thirdHeading">W3path.com</h3>'+
        '<div id="bodyContent">'+
        '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>'+
        '</div>'+
        '</div>';
    
        var infowindow = new window['google'].maps.InfoWindow({
            content: contentString
        });
    
        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });
        
    }    
  
    render() {
  
      return (
        <div className="row mt-5">
            <div className="col-md-10 mx-auto">
                <h2 className="text-left">Google Map</h2>
                <div className="card mt-3">
                    <div className="card-body">
                        <div ref="map" style={{'width':'100%', 'height':'400px' }}></div>
                    </div>
                </div>
            </div>
        </div>
      );
    }
  }
  


export default App;

Running application:

Run application using npm start and you should see Google Map inside browser. Congrats!! See, it was easy.

4 Comments

  1. Divine said:

    Great lesson. I love this…

    July 7, 2019
    Reply
  2. Our Web Page said:

    I truly wanted to post a brief comment to be able to thank you for some of the lovely pointers you are sharing at this site. My incredibly long internet search has at the end of the day been honored with excellent facts and techniques to share with my good friends. I ‘d express that most of us site visitors are really lucky to exist in a wonderful site with so many special people with insightful tips and hints. I feel rather blessed to have come across your site and look forward to so many more entertaining moments reading here. Thanks a lot once more for all the details.

    November 3, 2019
    Reply
  3. Debora said:

    Wood home furniture has one thing quite natural regarding it.
    There is this sense of comfort, of attribute as well as of elegance that can easily be actually be discovered in hardwood home furniture.
    Wood is born from the earth.

    My blog: get more info

    November 26, 2020
    Reply
  4. Paulina said:

    Just how will you like to bypass the high list prices at
    the household furniture establishments by using
    wood furnishings plans as well as make some on your own? It is achievable as well as a ton of individuals are actually already doing it.

    As resisted of what lots of people presume, it is actually not
    needed to become a pro to create timber furniture.

    Here is my blog post learn more

    November 28, 2020
    Reply

Leave a Reply

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