DEV Community

jessicabetts
jessicabetts

Posted on • Updated on

React Google Maps How to use the Google Maps API with React.js

hello-class

While trying to implement the google maps API in a personal react.js project I came across a couple of examples that I found to be very complicated and confusing. So here is a brief and simple example of how I used Google Maps in my app!

First, things first!

Go to the Google maps API page, sign-up and get a token to use! You must enter a credit card number to receive your token. However, Google claims they will not charge your account without you personally upgrading your service. Proceed at your own discretion.

Once you have an API key you can start building your app!

Create your react app

npm init react-app my-app
Enter fullscreen mode Exit fullscreen mode

Install dependencies

npm install --save google-maps-react
Enter fullscreen mode Exit fullscreen mode

This is how we get the google map as a component!
Check your package.json file to make sure it is installed!

Once your initial set up is done you can start coding!

1. Import google-maps-react!

import { Map, GoogleApiWrapper } from 'google-maps-react';
Enter fullscreen mode Exit fullscreen mode

2. Add the Map Component to your render function!

render() {
    return (
        <Map
          google={this.props.google}
          zoom={8}
          style={mapStyles}
          initialCenter={{ lat: 47.444, lng: -122.176}}
        />
    );
  }
Enter fullscreen mode Exit fullscreen mode

3. Edit your export default statement

export default GoogleApiWrapper({
  apiKey: 'TOKEN HERE'
})(MapContainer);
Enter fullscreen mode Exit fullscreen mode

Make sure to insert your API key here!

4. Add styling

If you'd like you can change some style properties. I did as a constant variable outside of my class.

const mapStyles = {
  width: '100%',
  height: '100%',
};
Enter fullscreen mode Exit fullscreen mode

5. Spin up your server!

google-maps-API

Great! You did it! But honestly, what is the point of a map without any markers! So let's add some!

6. Mark it up!

import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';
Enter fullscreen mode Exit fullscreen mode

Update your Map component to include a Marker Component!

render() {
    return (
        <Map
          google={this.props.google}
          zoom={8}
          style={mapStyles}
          initialCenter={{ lat: 47.444, lng: -122.176}}
        >
          <Marker position={{ lat: 48.00, lng: -122.00}} />
        </Map>
    );
  }
Enter fullscreen mode Exit fullscreen mode

Then you'll have this!

google-map-with-marker

Let's add more!

Instead of adding one marker, you can programmatically loop through the state to display places. In my example, I am displaying a few thrift stores in the area. You can also add events to them such as onClick!

export class MapContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      stores: [{lat: 47.49855629475769, lng: -122.14184416996333},
              {latitude: 47.359423, longitude: -122.021071},
              {latitude: 47.2052192687988, longitude: -121.988426208496},
              {latitude: 47.6307081, longitude: -122.1434325},
              {latitude: 47.3084488, longitude: -122.2140121},
              {latitude: 47.5524695, longitude: -122.0425407}]
    }
  }

  displayMarkers = () => {
    return this.state.stores.map((store, index) => {
      return <Marker key={index} id={index} position={{
       lat: store.latitude,
       lng: store.longitude
     }}
     onClick={() => console.log("You clicked me!")} />
    })
  }

  render() {
    return (
        <Map
          google={this.props.google}
          zoom={8}
          style={mapStyles}
          initialCenter={{ lat: 47.444, lng: -122.176}}
        >
          {this.displayMarkers()}
        </Map>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

And that's all folks!

google-map-with-many-markers

I hope this tutorial helps in building your own app!

Top comments (46)

Collapse
 
titivermeesch profile image
PlayBossWar

Thanks a lot for this!
I had to do a little research for the styling since I wanted to use their custom json style files.
A little tip for those who want to do this too : save it as a defaultProps and they use it as shown above ;)

Collapse
 
cuzureau profile image
Christophe Uzureau

Hey ! Can you tell me more about this ? Where do you pass defaultProps ?

Collapse
 
titivermeesch profile image
PlayBossWar

Here is a link to the file I used it in, it will help you out I think : github.com/titivermeesch/neighbora...

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
cuzureau profile image
Christophe Uzureau • Edited

Thanks a lot, it helped me !
Le Bonjour à la Belgique :)

Collapse
 
sarabs3 profile image
Sarabjeet Singh

Thanks a lot. It's very easy to follow and implement.

Collapse
 
jessicabetts profile image
jessicabetts

Glad I can help!

Collapse
 
dschulz1227 profile image
Damon Schulz

I am trying to hide my API key by putting it in a default.json in a Config folder and hiding it. it's under my 'src' folder, but when I go to import it to my Map component, it says it is outside of the project '/src' directory. I've tried numerous ways, do you have any idea what I should do?

Collapse
 
sanjayjb profile image
sanjayjb

Hey! Thanks a lot for the Maps implementation.
I was wondering how Polygon can be used from google-maps-react to mark a triangle on the map using 3 lat and long coordinates. could you please help me out with that?
thanks in advance :)

Collapse
 
sayanmondal2098 profile image
PH3N1X

Thanks for it.

Collapse
 
barcarel profile image
anncarel

Very well done! Thanks for sharing.

Collapse
 
arinze090 profile image
arinze090

For some weird reason, my browser keeps saying “Loading maps”

Did exactly the same thing as displayed.
Any help ?

Collapse
 
hawicaesar profile image
HawiCaesar

Hey Jessica, thanks for the tutorial. You've quite a lot here.

By any chance have you ever tried configuring autocomplete/places with the markers using google maps react ?

Collapse
 
rosscatley72 profile image
Ross Catley

Great article. I'm stuck on a specific next step, I wonder if anyone can help me.

I've added a polyline to the map, and want a user to be able to edit it. That bit is fairly straightforward you use the {Polyline} component and add it to the map the same way as the Marker in the article, and set the editing prop to true.

What I've been trying to find the answer to for days now is how I then access the getPath() method once the user has finished editing the line to access the LatLng points that the user has edited on the line.

I've tried adding a ref={} on the polyline itself, and although I can access the coordinates of the line from that, after editing the coordinates return the original coordinates and not the user edited LatLng of the updated polyline.

I'm trying to keep to using functional hooks, and all the examples I can find (and there are only a couple of them) seem to use the native Javascript API within classes rather than a react component. If that's the only way to do it then I'll stick to that, but I can't find any documentation that talks about the React library and the getPath() method, or the "set_at" or "insert_at" events that fire on the path of the polyline when a user moves or adds a new point.

Has anyone done this or knows how to do it, I would be really grateful for any help.

Collapse
 
jothamardel profile image
jothamardel

Awesome.

Collapse
 
richwag profile image
Rich Wagenknecht

Nicely done! Very clear and to the ponit.

Collapse
 
jessicabetts profile image
jessicabetts

Thank you!

Collapse
 
fra profile image
Flavio Fraschetti

Thank you!

Collapse
 
shrsabin profile image
Sabin Stha

Is it possible to use legends on it.

Collapse
 
jessicabetts profile image
jessicabetts

Not sure! Never tried!

Collapse
 
btcbot_in profile image
BtcHodler

please write about google address auto suggestion fill form filed in react

Collapse
 
am_stevenanongo profile image
stevenanongo

This was really helpful to me thanks a lot