1

I am trying to render a map on a page using React but the map never displays. In console I can see this warning and it seems that the variable is not called anywhere. I have seen common implementations like this work on tutorials but I dont understand why it's not rendering here.

This is my App component code:

import React, {Component} from 'react';
import './App.css';

class App extends Component {

  componentDidMount() {
      this.renderMap();
  }

  renderMap = () => {
      this.loadScript("https://maps.googleapis.com/maps/api/" +
        "js?key=AIzaSyC1FpwqY0kv0hxQYPtGnn54ag14jHUI6Ow&callback=initMap");
      window.initMap = this.initMap;
  };

  loadScript = (url) => {
      const index = window.document.getElementsByTagName("script")[0];
      const script = window.document.createElement("script");
      script.src = url;
      script.async = true;
      script.defer = true;
      index.parentNode.insertBefore(script, index);
  };

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

  render() {
      return (
          <div className="App">
              <h1>Google Maps in React App</h1>
              <div id="map"> </div>
          </div>
      );
  }
}

export default App;

This is the warning in console:

webpackHotDevClient.js:120 ./src/App.js
Line 26:  'map' is assigned a value but never used  no-unused-vars

I have loaded the script in the component dynamically. Can someone help me out? Thanks.

0

1 Answer 1

3

That just means that you defined the variable map, but don’t use it. This warning comes from eslint and not google maps. In initMap, you may just add return map

Additionnally, you can also disable this eslint rule in your eslint config as explained here

Sign up to request clarification or add additional context in comments.

5 Comments

I have returned map but still not rendering. Another issue arose where I created a new api key and I'm getting a quota limit exceeded error. How do I solve these problems? Thanks
Your map may never render... I think you won’t be able to use these Api keys because they have used the maximum quota of Google maps for that account. This is independant from your code and could require another question on SO
Ok, thanks. Back to the issue on this question. Pls tell me why it still does not render even though the key is in order
Are you getting a message in the console.log? You may see this answer I wrote some time ago
I have solved this by using npm pkg - react-google-maps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.