我正在尝试使用 react-google-maps,在 DirectionsService 中有一个结果,并且结果有一些我需要的信息,但即使我分配给全局变量,我也不能在 DirectionsService 之外使用它。我只想在下面的返回函数中使用它。如何定义 DirectionsService 之外的可变路由?
/*global google*/
import React from 'react'
import { compose, withProps, lifecycle } from 'recompose'
import {withScriptjs, withGoogleMap, GoogleMap, DirectionsRenderer}
from 'react-google-maps'
var origin1;
var origin2;
var destination1;
var destination2;
var routes;
class MyMapComponent extends React.Component {
constructor(props){
super(props)
}
render() {
origin1 = this.props.origin1
origin2 = this.props.origin2
destination1 = this.props.destination1;
destination2 = this.props.destination2;
const DirectionsComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?
key=AIzaSyDSMDeXXQxaeLJ4ZGXuwSKAM3NHBP4ckTc",
loadingElement: <div style={{ height: `400px` }} />,
containerElement: <div style={{ width: `100%` }} />,
mapElement: <div style={{height: `500px`, width: `500px` }} />,
}),
withScriptjs,
withGoogleMap,
lifecycle({
componentDidMount() {
const DirectionsService = new google.maps.DirectionsService();
DirectionsService.route({
origin: new google.maps.LatLng(destination1, destination2),
destination: new google.maps.LatLng(origin1, origin2),
travelMode: google.maps.TravelMode.DRIVING,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
routes = result.routes[0].legs[0]
this.setState({
directions: {...result},
markers: true,
})
} else {
console.error(`error fetching directions ${result}`);
}
console.log("defined: ", routes)
});
console.log("undefined: ", routes) // why it is defined
}
})
)(props =>
<GoogleMap
defaultZoom={3}
>
{props.directions && <DirectionsRenderer directions= .
{props.directions} suppressMarkers={props.markers}/>}
</GoogleMap>
);
return (<div>
<DirectionsComponent
/>
<div>{routes.distance.text}</div> // I want to use here but routes is undefined
</div>
)
}
}
export default MyMapComponent