Search code examples
reactjsgoogle-mapsreact-google-maps

How to set travel mode of google directions api dynamically in reactjs?


I am trying to update the travel mode dynamically based on the selected radio buttons.

I have read the documentations of the directions api and have tried the following.

class Transport extends React.Component {
  state={
    origin: '',
    destination: '',
    directions: '',
    mode: 'DRIVING'
  }

  setDirections(){
    const DirectionsService = new google.maps.DirectionsService();

      DirectionsService.route({
        origin: this.state.origin,
        destination: this.state.destination,
        travelMode: google.maps.TravelMode[this.state.mode]
      }, (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          this.setState({
            directions: result,
          });
        } else {
          console.error(`error fetching directions ${result}`);
          alert('Selected mode of transport is not available for the for the trip!');
        }
      });
  }

  showPlaceDetails(place) {
    let destination = sessionStorage.getItem('city');
    destination=destination.replace(/\+/g, ' ');
    console.log(destination);
    let origin = place.address_components[0].long_name.toString();
    try{
        origin+= ' ' + place.address_components[2].long_name.toString();
    }catch(e){}
    console.log(origin);

    this.setState(() => ({origin, destination}));

    this.setDirections();
}

onModeChange = (e) =>{
  const mode = e.target.value;
  console.log(mode);

  this.setState(() => ({mode}));

  this.setDirections();
}

   render() {
   const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap
        defaultCenter = { { lat: 40.756795, lng: -73.954298 } }
        defaultZoom = { 13 }
      >
      {this.state.directions && <DirectionsRenderer directions={this.state.directions} />}
      </GoogleMap>
   ));
   return(
      <div>
        <div className='travel-details-container'>
          <div>
            <CitySuggestionBar onPlaceChanged={this.showPlaceDetails.bind(this)} />
            <div>
            <label htmlFor="driving">Driving</label>
            <input type="radio" name="transport-type" id="driving" value="DRIVING" 
            onChange={this.onModeChange} defaultChecked />
            <label htmlFor="transit">Bus/Train</label>
            <input type="radio" name="transport-type" id="transit" value="TRANSIT"
            onChange={this.onModeChange} />
            <label htmlFor="air">Airways</label>
            <input type="radio" name="transport-type" id="air" value="AIRWAYS"
            onChange={this.onModeChange} />
          </div>
          </div>
        </div>
        <GoogleMapExample
          containerElement={ <div style={{ height: `500px`, width: '100%' }} /> }
          mapElement={ <div style={{ height: `100%` }} /> }
        />
      </div>
   );
   }
};

I have set the default mode to DRIVING in the state and the default radio checked is also DRIVING. However, when I change it to Bus/Train it still appears to be driving on the map. But, the most confusing things is when I switch back to driving the map now updates to Transit and the mode in the state is driving.

Please Help! Thanks in advance.


Solution

  • This is likely due to setState being asynchronous as described in the State and Lifecycle documentation. By calling this.setDirections() immediately following this.setState, this.state.mode will have the old state value until the asynchronous update completes. To address this, setState takes a second argument for a callback function that will run after the state update completes (see here). You can use this like this.setState({ mode }, () => this.setDirections()). Alternatively, you could use componendDidUpdate and check if any dependent values changed and then call this.setDirections().