首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用react-google-maps实现多个航点

使用react-google-maps实现多个航点
EN

Stack Overflow用户
提问于 2017-10-12 03:45:15
回答 1查看 386关注 0票数 1

当使用react-google-maps库时。我已经找到了DirectionsRenderer,但我只看到选项中包含了一个起点和一个目的地。

是否可以包含多个路点?

Google Maps API Docs

EN

回答 1

Stack Overflow用户

发布于 2021-10-07 01:13:15

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

以下是示例代码片段:

代码语言:javascript
运行
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46696324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档