Display Directions with React Google Maps

A. Andersen picture A. Andersen · Feb 24, 2019 · Viewed 13.6k times · Source

I am new to React and am attempting to use google maps to display directions. I have been able to get it to display a single marker but have not found how to reconfigure the code to display the directions. Below is my most recent attempt but it will only display the map... any assistance is appreciated:

import React, { Component } from 'react';
import { withGoogleMap, GoogleMap, DirectionsRenderer } from 'react-google-maps';
class Map extends Component {
   render() {
   const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap
        defaultCenter = { { lat: 40.756795, lng: -73.954298 } }
        defaultZoom = { 13 }
      >

<DirectionsRenderer origin={{ lat: 40.756795, lng: -73.954298 }} destination={{ lat: 41.756795, lng: -78.954298 }} />
      </GoogleMap>
   ));
   return(
      <div>
        <GoogleMapExample
          containerElement={ <div style={{ height: `500px`, width: '500px' }} /> }
          mapElement={ <div style={{ height: `100%` }} /> }
        />
      </div>
   );
   }
};
export default Map;

I have the API key in a script tag in index.html

Answer

Vadim Gremyachev picture Vadim Gremyachev · Feb 25, 2019

DirectionsRenderer component does not accept origin and destination props, directions prop needs to be provided instead which value represents the response from DirectionsService, for example:

<DirectionsRenderer
      directions={this.state.directions}
 />

where

const directionsService = new google.maps.DirectionsService();

const origin = { lat: 40.756795, lng: -73.954298 };
const destination = { lat: 41.756795, lng: -78.954298 };

directionsService.route(
  {
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.DRIVING
  },
  (result, status) => {
    if (status === google.maps.DirectionsStatus.OK) {
      this.setState({
        directions: result
      });
    } else {
      console.error(`error fetching directions ${result}`);
    }
  }
);

Demo