Search code examples
reactjsgoogle-mapsgoogle-maps-api-3react-google-maps

React Google Map with DirectionsRendered, how to pass directions props?


I have a problem with react-google-maps map with DirectionRenderer. I tried to pass directions props in many ways but I always get this error:

InvalidValueError: setDirections: in property routes: not an Array

I defined like below:

state= {
      a: new google.maps.LatLng(41.8507300, -87.6512600),
      b: new google.maps.LatLng(41.8525800, -87.6514100)
};

and then passed here but got the error described

<MapWithADirectionsRenderer 
       directions={ how to pass here? } />

I have also another problem: I get this error :

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

I included script tag to api google in public_html/index.html and also on the component MapWithADirectionsRenderer on googleMapURL requested params like in the official example (https://tomchentw.github.io/react-google-maps/#directionsrenderer). I cannot remove the script on index.html because if I remove it I get the 'google undefined error' . I used /*global google */ at the start of the file the I use 'new google.maps..ecc like described on another stack overflow post.


Solution

  • I finally solved like below by modifying standard code from

    DirectionsService.route({
        origin: new google.maps.LatLng(41.8507300, -87.6512600),
        destination: new google.maps.LatLng(41.8525800, -87.6514100),
        travelMode: google.maps.TravelMode.DRIVING,
      }, (result, status) => {
        etc etc
      });
    

    to

    DirectionsService.route({
        origin: this.props.origin,
        destination: this.props.destination,
        travelMode: google.maps.TravelMode.DRIVING,
      }, (result, status) => {
         etc etc
      });
    

    and the pass origin and destination props like so

    <MapWithADirectionsRenderer
        origin={this.state.origin} destination={this.state.destination} /> 
    

    Now it works good!