DirectionsRenderer,将出发地和目的地作为道具

时间:2018-11-15 14:52:43

标签: reactjs google-maps

我正在使用DirectionsRenderer react-google-maps库在两点之间渲染目的地。我想在生命周期componentDidMount函数内传递针对起点和终点的自定义道具,但是起点和终点的pathCoordinates抛出错误,表示未定义。传递此信息以呈现目的地和起点标记位置的最佳方法是什么。

... all the right imports

const Map = compose(
    withGoogleMap,
    lifecycle({
        componentDidMount() {
            const DirectionsService = new google.maps.DirectionsService();

            DirectionsService.route({
                origin: pathCoordinates[0],
                destination: pathCoordinates[1],
                travelMode: google.maps.TravelMode.DRIVING,
            }, (result, status) => {
                if (status === google.maps.DirectionsStatus.OK) {
                    this.setState({
                        directions: result,
                    });
                } else {
                    console.error(`error fetching directions ${result}`);
                }
            });
        }
    })
)(props =>
    <GoogleMap
        defaultZoom={13}
        defaultCenter={props.pathCoordinates[0]}
    >
        {props.directions && <DirectionsRenderer directions={props.directions} />}
    </GoogleMap>
);

class MapOverlay extends Component {
    render() {
        const trip = this.props.trip;

        return (
            trip.status !== '' ?
                <Map
                    containerElement={<div style={{ height: `400px` }} />}
                    mapElement={<div style={styles.map} />}
                    pathCoordinates={
                        [
                            { lat: trip.pickUp.coordinates[1], lng: trip.pickUp.coordinates[0] },
                            { lat: trip.dropOff.coordinates[1], lng: trip.dropOff.coordinates[0] }
                        ]
                    }
                />
                : null
        );
    }
}

1 个答案:

答案 0 :(得分:1)

可以通过this.props.pathCoordinates访问这些道具:

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

    DirectionsService.route({
      origin: this.props.pathCoordinates[0], 
      destination: this.props.pathCoordinates[1], 
      travelMode: google.maps.TravelMode.DRIVING,
    }, (result, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        this.setState({
          directions: result,
        });
      } else {
        console.error(`error fetching directions ${result}`);
      }
    });
}

Demo