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












0















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.










share|improve this question



























    0















    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.










    share|improve this question

























      0












      0








      0








      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.










      share|improve this question














      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.







      reactjs google-maps react-google-maps






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 30 '18 at 14:09









      rajput sufiyaanrajput sufiyaan

      246




      246
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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().






          share|improve this answer
























          • Thank you very much for the information. It worked!

            – rajput sufiyaan
            Dec 31 '18 at 16:24











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53978297%2fhow-to-set-travel-mode-of-google-directions-api-dynamically-in-reactjs%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          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().






          share|improve this answer
























          • Thank you very much for the information. It worked!

            – rajput sufiyaan
            Dec 31 '18 at 16:24
















          0














          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().






          share|improve this answer
























          • Thank you very much for the information. It worked!

            – rajput sufiyaan
            Dec 31 '18 at 16:24














          0












          0








          0







          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().






          share|improve this answer













          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().







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 31 '18 at 3:20









          TylerTyler

          1,02627




          1,02627













          • Thank you very much for the information. It worked!

            – rajput sufiyaan
            Dec 31 '18 at 16:24



















          • Thank you very much for the information. It worked!

            – rajput sufiyaan
            Dec 31 '18 at 16:24

















          Thank you very much for the information. It worked!

          – rajput sufiyaan
          Dec 31 '18 at 16:24





          Thank you very much for the information. It worked!

          – rajput sufiyaan
          Dec 31 '18 at 16:24


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53978297%2fhow-to-set-travel-mode-of-google-directions-api-dynamically-in-reactjs%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Mossoró

          Error while reading .h5 file using the rhdf5 package in R

          Pushsharp Apns notification error: 'InvalidToken'