我正在使用DirectionsRenderer react谷歌地图库来渲染两点之间的目的地。我想在生命周期组件DidMount函数中传递源和目的地的自定义道具,但源和目的的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
);
}
}
这些道具可以通过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}`);
}
});
}
演示