如何在react-google-maps中使用DirectionsService中的变量路由?

时间:2018-05-21 01:01:30

标签: react-google-maps

我正在尝试使用react-google-maps,在DirectionsService中有一个结果,结果有一些我需要的信息,但即使我分配给全局变量,我也无法使用DirectionsService。我只想在下面的return函数中使用它。如何定义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

0 个答案:

没有答案