如何在 reactjs 中动态设置 google 方向 api 的出行模式?

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

我正在尝试根据所选的单选按钮动态更新出行模式。

我已经阅读了说明的文档 api 并尝试了以下方法。

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>
   );
   }
};

我在状态下设置了默认模式为DRIVING,默认勾选的收音机也是DRIVING。但是,当我将其更改为 Bus/Train 时,它似乎仍在地图上行驶。但是,最令人困惑的是,当我切换回驾驶时,地图现在更新为 Transit,并且状态模式为驾驶。

请帮忙! 提前致谢。

这可能是因为 setState 是异步的,如 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 中所述)。您可以像 this.setState({ mode }, () => this.setDirections()) 这样使用它。或者,您可以使用 componendDidUpdate 并检查是否有任何相关值发生更改,然后调用 this.setDirections().

您可以使用 JavaScript 动态更改出行模式。请检查代码如下:

在HTML中给出选择框如下:

<select class="form-control" id="mode">
  <option value="">Select Mode</option>
  <option value="WALKING">Walking</option>
  <option value="DRIVING">Driving</option>
  <option value="BICYCLING">Bicycling</option>
  <option value="TRANSIT">Transit</option>
</select>

在JavaScript的initMap()函数中,添加如下:

  document.getElementById("mode").addEventListener("change", () => {
    calculateAndDisplayRoute(directionsService, directionsRenderer);
  });

这里,calculateAndDisplayRoute是JavaScript中的一个独立函数:

function calculateAndDisplayRoute(directionsService, directionsRenderer)
{
  var selectedMode = document.getElementById("mode").value;
  directionsService.route(
    {
      origin: Your Origin Values,
      destination: Your Destination Values,
      travelMode: google.maps.TravelMode[selectedMode]
    },
    (response, status) => {
      if (status == "OK") {
        directionsRenderer.setDirections(response);
      }
      else {
        window.alert("Directions request failed due to " + status);
      }
    }
  );
}