DEV Community

Allen Shin
Allen Shin

Posted on

Google maps on React

This week I wanted to add a page to my grocery store application where you could show the location of the store using google maps. I tried using the Google maps Javascript API documentation, which asks you to load a script tag with the API url and key, but that led to some CORS issues for me. Based on some articles that I read, it had something to do with the issue of not being able to run the script from a front end application. So, I ended up using a library called Google Maps React which allows you to hook up the Google Maps API directly to your components.

Getting the API Key

You still need access to an API key in order for you to gain access to this library so you'll want to head over to the Google's developer console in order to sign up for an account and get the API key.

After you're connected, you will want to enable certain API's that you want to use, and for my own purposes, I enabled the Maps Javascript API and the Geocoding API. The first is for the actual rendering of the map, and the second is for converting addresses into coordinates.

Lastly, you will want enable a billing account, where you have to give your credit card information. You won't get charged intially since there is a free trial of 3 months during which you get 300 dollars worth of credit. Very pricey, and thinking of looking for other solutions, before the free trial is over.

Google Maps React

Once you get your API key you have everything you need to use Google Maps React. If you want to see the full documentation, it is available on their npm page.

First install the library
npm install google-maps-react

Alt Text

Here are some of the imports that I used for my map component, the required ones being the Map and GoogleApiWrapper.

Alt Text

This is the component itself. I ended up using the markers for marking out where my stores were and obviously the map component intself. The properties of concern for my app were the initialCenter of the map component and position attributes for the markers. I wanted the map to start on the store's location and the markers to mark out the user's location and store's location.

The user's location was using the navigator object available on the browser, and the store's location was using sending parameters of the store's address to the Geocoding API I enabled. Both of these return object literals that have 'lat' and 'lng' properties, that can be passed into the respective component properties to get our desired map configuration.

Alt Text

Last but not least we have our API's export statement, which we need to insert our API key. I simply wrote a note here, but you'll want to hide it in an env file which is git ignored so that it's hidden.

Alt Text

And there you have it! Google Maps on your React app.

Top comments (0)