Using Geocode API to Plot Markers on Your React Google Map

Today’s article will be building off of last week’s article about implementing the Maps JavaScript API. If you haven’t already read that, you can find it here. It’s essential to this guide as I’ll be using previously built functions and components. Without further ado, let’s jump in.

As always, if you want this paraphrased information straight from the source, follow this link to the documentation.

Activate the API

So first things first, you need to activate this API in the Google Dev Console, the same way you did in the last walkthrough. You can use JavaScript’s native fetch() method in this walkthrough. However, I’ll be using a fetching library called axios.

Making the Request

The first thing I want to cover is the base for the request URI. The example given by the docs shows this string:

The outputFormat is going to be replaced with json. You have the option to return either a JSON or XML response, and I find JSON much easier to work with.

The parameters section of the string will be replaced with

address=<ADDRESS />. The actual address of the string needs to be broken up and separated, however. The street address and the city (if more than one word) need to be formatted by replacing spaces with +. Then, the street address, city, and state need to be separated by commas. Below is an example of the request I’ll be making using the address of the Youngsville Sports Complex in Louisiana:

Getting this string URL is the end goal. This string is what I’ll need to use in my request to get the geographical location of the Sports Complex.

Implementing The Request

Application State and Data Entry

The general idea I have for this implementation is to have three fields: one for the street address, the city, and the state. You’ll type in a street address, then a city, then select a city from a drop down and then plot that Marker on the Map.

The first thing I want to do is update the initial state to hold whatever address we want to plot:

This object is the raw data we are going to pass to the function that actually sends the request to the Google API. Next let’s build the inputs:

You need the set of states in your application’s initial state. The formatting will be a little wonky, but this is it:

We need a handful of functions now. One to generate our state options, another to persist whichever option was selected to the application state, one to track input changes, and the final one to handle when this information is submitted:

If you need to keep any of these commented out for now, don’t worry, we’ll define them later so they won’t cause errors if they’re doing that now.

IMPORTANT NOTE: Always make sure to include ...this.state.location or whatever similar key needed for nested attributes in your application state. This will cause the previous state to be persisted and not overwritten when you change another value.

Next we need to update our <select /> tag.

Feel free to rename any of that if need be. Seeing the word “state” that many times can be a little confusing.

Building the Request Function

If you’ve held on this far, I have good news. We are almost there! Let’s get into our function, getGeocode(). This function is going to be async, it’ll accept our state.location object as an argument, and will then update the application state, causing a re-render with our newly added destination.

If everything you did above is working right, the location object that we pass will look just like this:

So then we’ll need the getGeocode() function from above:

I always find this as a good starting point. I’d recommend running this function at this point to make sure everything is in order. The address and city (if more than one word) will have their whitespace removed and replaced with + in order to match the format I showed at the beginning.

The next piece we need is the demo string, but we also need to interpolate the above values. Additionally, since our function is async, we can set up our fetch with the keyword await to make sure that we get our return value before moving on in the function. This updated version will probably be poorly formatted since the url string will be long, but I’ll do my best to make it readable:

Now we should have our data values separated an inserted into the string. The reason I’m still using console.log here is because if the url string is properly interpolated, you can then copy it from the console and paste it to your browser to then see the response. As long as you have a browser extension that parses JSON, it’ll make this entire response so much easier to look at. This is an example of when I did it:

I collapsed some of the attributes for readability. The important place to look is at the formatted_address and geometry.

So if you’re looking at this in your browser, then congrats! I promise you, we are so close to having this how we want it.

The Final Stretch

All we have left to do is send the actual request and then use the return data to render our Marker. Finally! Let’s wrap this up:

Let’s walk through this step by step now that it’s finished.

  1. Setting up our variables to interpolate
  2. Setting up the URL string by interpolating our address, city, state, and API Key
  3. Initializing a response variable that uses await to make sure we have a resolved Promise before moving on
  4. The data variable targets the results that we received
  5. Then initialize a coords variable that contains the response information needed for the Marker.
  6. Return that value.

We just have ONE MORE STEP. And that step is to then take the return value and persist it to our application state, that way our Marker actually renders. To do that, we simply chain a .then() to where we call getGeocode(). Like so:

And there you have it! If everything was done correctly, now when you submit a location, it should render a new marker on the Map. And as an added bonus, the InfoWindow should also pull up on any new rendered Marker!

Conclusion

All of the functionality we just built incorporates with the renderDestinations() function from the last article because React updates on every state change. This takes advantage of that feature by seamlessly forcing a re-render by updating the component’s state with a new Marker. If you want Markers to render initially, you just add them as an object with lat and lng keys that points to its geographic location to your component’s initial state.

Thank you for taking the time to read, I hope this helped you learn something new. If for some reason your are having difficulty implementing this at any point, leave a comment and I can try to help you through it. Happy coding!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store