使用 React Google Maps 显示方向

A. *_*sen 4 google-maps reactjs react-google-maps

我是 React 的新手,正在尝试使用谷歌地图来显示方向。我已经能够让它显示单个标记,但还没有找到如何重新配置​​代码以显示方向。以下是我最近的尝试,但它只会显示地图......感谢任何帮助:

import React, { Component } from 'react';
import { withGoogleMap, GoogleMap, DirectionsRenderer } from 'react-google-maps';
class Map extends Component {
   render() {
   const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap
        defaultCenter = { { lat: 40.756795, lng: -73.954298 } }
        defaultZoom = { 13 }
      >

<DirectionsRenderer origin={{ lat: 40.756795, lng: -73.954298 }} destination={{ lat: 41.756795, lng: -78.954298 }} />
      </GoogleMap>
   ));
   return(
      <div>
        <GoogleMapExample
          containerElement={ <div style={{ height: `500px`, width: '500px' }} /> }
          mapElement={ <div style={{ height: `100%` }} /> }
        />
      </div>
   );
   }
};
export default Map;
Run Code Online (Sandbox Code Playgroud)

我在 index.html 的脚本标签中有 API 密钥

Vad*_*hev 8

DirectionsRenderer组件不接受origindestination道具,directions需要提供道具代替哪个值代表来自 的响应DirectionsService,例如:

<DirectionsRenderer
      directions={this.state.directions}
 />
Run Code Online (Sandbox Code Playgroud)

在哪里

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

const origin = { lat: 40.756795, lng: -73.954298 };
const destination = { lat: 41.756795, lng: -78.954298 };

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

演示