【问题标题】:Multiple Waypoints with react-google-maps带有 react-google-maps 的多个航点
【发布时间】:2018-03-23 14:34:20
【问题描述】:

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

是否可以包含多个航点?

Google Maps API Docs

【问题讨论】:

  • 仅供任何访问者参考...这个项目是 React 和 Laravel Blade 视图的混合,因此维护者的响应基本上是“弄清楚”。这完全没问题(他提供的工具可以满足我 80% 的需求)。这个特定项目的预算没有包括解决这个问题,所以我只是退出了 React 并切换回遵循 google 提供的示例的基本视图。

标签: reactjs google-maps react-google-maps


【解决方案1】:

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

这是一个示例代码 sn-p:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-11
    • 2018-05-10
    • 1970-01-01
    • 2016-04-20
    • 2017-05-14
    • 2012-06-21
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多