反应和谷歌Directions API没有地图

时间:2020-07-08 19:37:28

标签: reactjs google-maps google-directions-api travel-time

我需要内部应用程序中.route()的结果,而不需要进入任何地图。我需要起点和终点之间的持续时间和距离,以便在我的应用中进行进一步的计算。

到目前为止,我已经使用回调函数进行了尝试:

function getTravelTime(origin, destination, cb) {
    const directionsService = new google.maps.DirectionsService();
    directionsService.route(
        {
            origin: origin,
            destination: destination,
            travelMode: "DRIVING"
        },
        (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                cb(null, {
                    duration: moment.utc(moment.duration(result.routes[0].legs[0].duration.value, 'seconds').as('milliseconds')).format('HH:mm'),
                    distance: result.routes[0].legs[0].distance.value
                });
            } else {
                cb('error');
                console.log(result);
            }
        }
    );
};

我试图这样阅读:

let tInfo = getTravelTime(origin, destination, function (err, dist) {
   if (!err) {
      let distanceBetweenLocations = dist.distance;
      let durationBetweenLocations = dist.duration;
      // Or with saving to a state
      setTravelInformation(prevState => ({
         distance: dist.distance,
         duration: dist.duration
      }));
    }
});  

是否有可能无需绘制地图即可计算距离和旅行时间?

到目前为止,我得到了这个结果,大大缩短了时间,因为我对同一文件中的其他组件有了更多的逻辑:

import {
withGoogleMap,
GoogleMap,
withScriptjs,
Marker,
DirectionsRenderer
} from "react-google-maps";

const getTravelTime = (origin, destination) => {
    const directionsService = new google.maps.DirectionsService();
    directionsService.route(
      {
        origin: origin,
        destination: destination,
        travelMode: google.maps.TravelMode.DRIVING
      },
      (result, status) => {
        console.log(result)
        if (status === google.maps.DirectionsStatus.OK) {
          setDirections(result);
        } else {
          setError(result);
        }
      }
    );
}  

我需要在HoC withScriptjs中使用我的组件并将其包装吗?

2 个答案:

答案 0 :(得分:0)

您可以使用useStateuseEffect,请参阅https://reactjs.org/docs/hooks-effect.html

const [distance, setDistance] = useState(0);
const [duration, setDuration] = useState(0);

useEffect(() => {
  if (distance && duration) {
    console.log("Distance & Duration have updated", distance, duration);
  }
}, [distance, duration]);

收到“路线”结果后,请使用所需的任何值更新距离和持续时间:

directionsService.route({
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.DRIVING
  },
  (result, status) => {
    if (status === google.maps.DirectionsStatus.OK) {
      setDistance(result.routes[0].legs[0].distance.value);
      setDuration(result.routes[0].legs[0].duration.value);
    } else {
      console.error("error fetching directions", result, status);
    }
  }
);

这是使用@react-google-maps/api

的有效代码段

https://codesandbox.io/s/react-google-mapsapi-directions-service-m7qif

如果不起作用,您需要使用有效的API密钥。

答案 1 :(得分:0)

    import React, { Component } from "react";
    import { withGoogleMap, GoogleMap, withScriptjs, DirectionsRenderer, Marker } from "react-google-maps";
    import { compose, withProps } from "recompose";
    import PropTypes from "prop-types";

    class MapDirectionsRenderer extends Component {
      static propTypes = {
        waypoints: PropTypes.array,
        places: PropTypes.array
      };

      state = {
        directionsRef: '',
        directions: null,
        error: null
      };

      componentDidMount() {
        const { places, origDest } = this.props;
        const waypointsArray = places.map(p => ({
          location: p.geocode,
          stopover: true
        }));
        const origin = origDest.origin_geocode;
        const destination = origDest.destination_geocode;
        const directionsService = new window.google.maps.DirectionsService();
        directionsService.route(
          {
            origin: origin,
            destination: destination,
            travelMode: window.google.maps.TravelMode.DRIVING,
            waypoints: waypointsArray.length >= 1 ? waypointsArray : [],
          },
          (result, status) => {
            if (status === window.google.maps.DirectionsStatus.OK) {
              this.setState({
                directions: result,
              });
            }
          }
        );
      }
      render() {
        return (
          this.state.directions && (
            <DirectionsRenderer
              directions={this.state.directions}
            />
          )
        );
      }
    }

    const MapView = compose(
      withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&v=3.exp",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `300px`, width: '100%' }} />,
        mapElement: <div style={{ height: `100%` }} />
      }),
      withScriptjs,
      withGoogleMap
    )(props => (
      <GoogleMap
        key={props.travelMode}
        defaultZoom={12}
        center={{ lat: 0, lng: 0 }}
      >
        <MapDirectionsRenderer
          places={props.wayPoints}
          origDest={props.originDestination}
        />
      </GoogleMap >
    ));

    export default MapView;