How to Use Google Distance Matrix API on front-end or back-end with React

Buena C
7 min readMay 5, 2018

--

For my four-day-long Stackathon project, I wanted to build an app that could take public content from Instagram posts via a hashtag search and render the geo-tagged locations in a user-friendly view for trip planning. For this, I used several Google map APIs including Google Distance Matrix with React-Redux. I found two different approaches to utilize the API while building my app, and will share both methods you can use depending on your situation. For beginners like myself, be sure to review the documentation provided by Google along with the information here.

The following two approaches can be used with the Google Distance Matrix

  • Use google-distance-matrix API on the back end
  • Use google-maps-react API on the front-end

Before starting, make sure you perform the following steps:

  • Create an API key via the Google API console
  • Go to the dashboard in the console and enable your API key

Using the API on the back-end

You will first need all information to send into the three required parameters at the minimum when calling to the Google API. Be sure to have the following ready:

  • Origin: provide in an array of strings including the latitude and longitude coordinates respectively (i.e. [‘42.30432’,’-73.4389'])
  • Destination(s): provide in an array of strings the latitude and longitude coordinates (you can send in multiple destinations in an array) (i.e. [‘42.30432,-73.4389',‘43.30432,-74.4389'])
  • Travel mode: provide in string format in uppercase one of the available choices (i.e. ‘WALKING’, ‘TRANSIT’,’BICYCLING’,’DRIVING’ )

Create a React class component. I’ve created a Search component in the example below. I also set up a local state on the component and initialized it with the expected data type. There is a form set up in this component that will be updated by the user based on the address and desired traveling method they input. I will not be focusing on this part in this article, but I used the Google Geocode API to convert their address into the latitude and longitude coordinates for use in my Google Distance Matrix API. The latitude and longitude results will then be set on my local state below.

Create your React component
  • This.state.lat and this.state.lng will be used to track my origin
  • This.state.travelMode will be used to track the user’s desired method of traveling

Both will be updated based on user inputs via a form on the component.

Next, set up your front-end to call to your back-end route

Create a function to call to your back-end route from the component

I invoke this function when the user has finalized all information that is required on the state (origin latitude, origin longitude and travel mode) and clicks a “submit search” button.

The getDistance function sends in my destinations (called posts), which are currently objects with the latitude and longitude as properties. The posts represent information received from all the user’s Instagram posts, including the geotag locations. I extract the latitude and longitude from each post object and format them into an array of strings. The final result would look something like this : [‘41.8337329,-87.7321554’, ‘41.8337329,-87.7321554’, ‘41.8337329,-87.7321554’].

Then, I use axios to call to my back-end post route. I use post so that I could send the required information to the back-end and have it readily available when calling to the API. Since I am sending a request to the back end, this will return a Promise, meaning I will need to use .then to wait for the response before running the following code. Lines 57 and 58 can be combined to be more DRY. Be sure to add an error handler in case an invalid response is returned. Putting in custom messages will also help you understand where the error is coming from much quicker.

Once I receive the response from the API, I grab the data off the response object by doing res.data. For this component, I used React-Redux and used connect to send props into my component. One of my props called ‘setDist’ utilizes dispatch to save the response in my store. I call this.props.setDist to dispatch the response data to my store. See below for how I set up my props.

I imported express which is connected via Router() to my middleware in a separate file. Be sure to export your router as well. Any time the front-end calls to /api/distance, the request will be directed into this file with my post route. You will also need to require the google-distance-matrix API into this file. You do not need a Google API key to access this particular API.

Set up your callback in the post route to grab the origin, destinations and travel mode from the request and send it into distance.matrix as multiple parameters named exactly the way I have above. This function also takes a callback as a parameter which is invoked based on the response provided by the API.

The below is an example of what the google distance matrix response will look like.

This is a sample response in JSON provided by Google distance-matrix documentation here

You will need to grab the rows from the object response (response.rows). You can further narrow it down to response.rows.elements. See line 14 in the previous image for the post route. Send the rows array in a res.json back to the front-end so you can then save the information as needed in your store (or wherever you need it).

If you provided the API with multiple destinations, the response will contain multiple objects in the elements array with the calculated distance and duration. The value provided is measured in seconds. If you prefer to include any additional information available through google-distance-matrix, you can do so by including additional arguments into the API request. See Google’s documentation for all additional options.

Using the API on the front-end

If you need to use the Google distance matrix entirely on the front-end with React, I would highly suggest utilizing the google map module specifically for React by npm installing react-google-maps. This provides a Google map wrapper for your component, which sends in all the tools Google maps provides including the distance matrix as props! Isn’t that great?! Check out the documentation in npm here. The instructions are fairly straightforward and digestable.

npm install react-google-maps

import {Map, InfoWindow, Marker, GoogleApiWrapper} from ‘google-maps-react’

Extract the required components you need from google-maps-react by importing them into your React component.

Map: a component that will build the actual google map and render it onto your page

InfoWindow: a component that will build the info bubble that pops up with details for a map marker when you click on the marker

Marker: a component that will build the marker to render onto your Map component

GoogleApiWrapper: essentially acts as your higher order function which replaces the “connect” functionality from React-Redux that typically wraps your component

Require the above components as needed

You will need a Google API key for this module since this utilizes several other Google Map APIs aside from the distance matrix. Store your key in a secrets file that will be gitignored and import it into the file.

Create your React class component as you normally would:

Set your state to any items you might need (i.e. address, latitude, longitude, etc)

Wrap your component in the GoogleApiWrapper provided by react-google-maps as such.

Normally, you would export default connect(mapStateToProps, mapDispatchToProps)(MapContainer) but now GoogleApiWrapper replaces connect and sends its own custom props in as methods for all the different google map APIs. If I console.log this.props in my component, I will see a property called “google” in my props object with access to all the maps methods. The same way we pulled these out of the react-google-map module by destructuring them in our import, we can also access them directly as methods.

If you want to set up your map, you can render the Map, Marker and InfoWindow components as such:

To access the distance matrix method provided by the google props, you can simply this.props.google.maps.getDistanceMatrix and send in the necessary parameters. If you take a closer look into the props, you will see what methods you have access to. I opened up the DistanceMatrixService key to see the methods made available on its internal prototype.

See how the getDistanceMatrix method is available on the internal prototype of DistanceMatrixService and requires two parameters (a and b)

For example, access the method as I have done below and send in the required parameters as needed. You will get the distances in the callback function the same way as I showed in the first approach on the back-end.

Access the method as such

You should also check if the response comes back with a status “OK”, otherwise it means something is invalid in your request.

There are many different ways you can access Google Maps APIs whether you install helpful npm modules for specific Google Map APIs or follow Google Map’s documentation to access their APIs via their suggestion.

Hope these tips gave you an understanding of what approach might be most helpful for you!

--

--