【问题标题】:DirectionsRenderer for origin and destination as propsDirectionsRenderer 用于作为道具的起点和终点
【发布时间】:2018-11-18 06:45:12
【问题描述】:

我正在使用 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
        );
    }
}

【问题讨论】:

    标签: reactjs google-maps


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多