如何在react.js中实现Google Route API?

时间:2019-03-09 01:30:42

标签: javascript reactjs google-maps google-maps-api-3

我遵循了this教程并实现了Google地图。我尝试使用Google Route API获取地图上两个位置之间的方向。但是我不确定我做错了什么,我得到了这个错误

  
    
      

1 |从“ ./Component”导入组件;错误

    
  
     

2 |从“反应”导入React;

     

3 |从“ react-dom”导入ReactDOM;

     

4 |从“ recompose”导入{compose,withProps,lifecycle};

这是我的代码

import Component from "./Component";
import React from "react";
import ReactDOM from "react-dom";
import { compose, withProps, lifecycle } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,

} from "react-google-maps";
import { DirectionsRenderer } from "react-google-maps";

const MapWithADirectionsRenderer = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=AIzaSyAcQjrfAudzl6Ton7GA7D-gVqOINMFE7ns =3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  withScriptjs,
  withGoogleMap,

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

      DirectionsService.route(
        {
          origin: new google.maps.LatLng(41.85073, -87.65126),
          destination: new google.maps.LatLng(41.85258, -87.65141),
          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={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
    {props.directions && <DirectionsRenderer directions={props.directions} />}
  </GoogleMap>
));

ReactDOM.render(
  < DirectionsRenderer directions />,
  document.getElementById("root")
);

0 个答案:

没有答案