1

使用react-google-maps图书馆时。我找到了DirectionsRenderer,但我只看到作为选项包含的起点和目的地。

是否可以包含多个航点?

谷歌地图 API 文档

4

1 回答 1

0

是的,您可以包含多个航点。正如您在DirectionsRenderer 示例中看到的,它使用const DirectionsService = new google.maps.DirectionsService();. 您可以按照DirectionsService 文档中的示例了解如何在您的请求中包含航点。

这是一个示例代码片段:

import React, { Component } from 'react';
import {
  withGoogleMap,
  GoogleMap,
  DirectionsRenderer,
} from 'react-google-maps';
class Map extends Component {
  state = {
    directions: null,
  };

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

    const origin = { lat: 40.756795, lng: -73.954298 };
    const destination = { lat: 41.756795, lng: -78.954298 };
    const waypt = [
      {
        location: { lat: 40.278022, lng: -76.899615 },
        stopover: true,
      },
      {
        location: { lat: 40.750216, lng: -78.922049 },
        stopover: true,
      },
    ];

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

  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>
        <GoogleMapExample
          containerElement={<div style={{ height: `500px`, width: '500px' }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />
      </div>
    );
  }
}

export default Map;
于 2021-10-07T01:13:14.957 回答